Servlets - filter, listeners, wrapper, internationalization


Published on

This presentation has introduction, advantages, and explanation of how to use these things. please read it give your suggestion....

Published in: Education, Technology, Business
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • * For entire web Apps
  • ServletRequestEventEvents are getServletRequest () and getServletContext() ServletRequestEvent is child class of java.util.EventObject
  • If u want to compress some response then we have to implement servletResponse interface and override all the methods , but we need only one or two … so java provides 4 wrapper classes,……..
  • <key>=<value> in a property file having new line char as separator….HELLO_MESSAGE= Hello, How r u ?HELLO_MESSAGE= Hallo, Wie geht es Ihnen??HELLO_MESSAGE= Hola, ¿Cómoestás?
  • Servlets - filter, listeners, wrapper, internationalization

    1. 1. Filters, Listeners, Wrappers, Internationalization. <br />By,<br />Susnatsahu<br />
    2. 2. Filters<br />Filters concept has introduced in Servlet 2.3 version.<br />A filter is a program that runs on the server before the Servlet or JSP page with which it is associated. A filter can be attached to one or more Servlet or JSP pages<br />and can examine the request information going into these resources.<br />Filters are used to preprocess the Request and post process the Response. <br />
    3. 3. Preprocessing involves <br /><ul><li>Authentication,
    4. 4. Logging,
    5. 5. Authorization,
    6. 6. Change request information , etc..</li></ul>Post processing involves <br /><ul><li>Compression of the response.
    7. 7. Encryption of the response.
    8. 8. To alter response information.</li></ul>Other Tasks<br /><ul><li>Security verification
    9. 9. Session validation
    10. 10. Internationalization
    11. 11. Data compression
    12. 12. MIME type changing</li></li></ul><li>Advantages of Filters<br />Encapsulate common behavior. <br /><ul><li>Have 30 different Servlet or JSP pages that need to compress their content to decrease download time? Make 1 compression filter and apply it to all 30 resources.
    13. 13. The filter class encapsulates the logic that has to be executed before or after the actual request processing, which is done by the requested resources.
    14. 14. The filter class is declared in the deployment descriptor.
    15. 15. It provides the ability to encapsulate recurring tasks in reusable units., Which allows us to modularize the code, which makes the code more manageable, documentable, easy to debug, and can be reused in other settings. </li></li></ul><li>Separate high-level access decisions from presentation code. <br /><ul><li> Want to block access from certain sites without modifying the individual pages to which these access restrictions apply? </li></ul> Create an access restriction filter and apply it to as many pages as you like.<br />Apply wholesale changes to many different resources.<br /><ul><li> Have a bunch of existing resources that should remain unchanged except that the company name should be changed?</li></ul> Make a string replacement filter and apply it wherever appropriate.<br />
    16. 16. The Filter Life Cycle<br />
    17. 17. Lets know about Filter API<br /> This API comprises of three interfaces <br /><ul><li>javax.servlet.Filter
    18. 18. javax.servlet.FilterConfig
    19. 19. javax.servlet.FilterChain</li></ul>javax.servlet.Filter<br /> Every Filter class must implement Filter interface either directly or indirectly. <br />
    20. 20. void init(FilterConfig filterConfig)<br /> <br /><ul><li>Initializes a filter and makes it ready for providing service.
    21. 21. The Servlet container calls the init method exactly once after instantiating the filter.
    22. 22. The web container cannot place the filter into service if the init method either</li></ul>1. Throws a ServletException 2. Does not return within a time period defined by the web container<br />
    23. 23. void doFilter (ServletRequestrequest, ServletResponse response, FilterChain chain)<br /> Encapsulates service logic to be implemented on ServletRequest to generate the ServletResponse. <br /> The FilterChain referncepassed as an argument to forwardrequest/response pair to the filter or targetresource of chain. <br />void destroy( ) <br /> Called by the web container to indicate to a filter that it is being taken out of service.<br />
    24. 24. <ul><li>javax.servlet.FilterConfig
    25. 25. Used during initialization of filter.
    26. 26. This object is used to fetch configuration information specified in web.xml
    27. 27.  String getFilterName()           Returns the filter-name of this filter as defined in the deployment descriptor. 
    28. 28. String getInitParameter(String name)           Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. </li></li></ul><li><ul><li>Enumeration getInitParameterNames() </li></ul>    Returns the names of the filter's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters. <br /><ul><li>ServletContextgetServletContext() </li></ul>   Returns a reference to the ServletContext in which the caller is executing.<br />
    29. 29. <ul><li>javax.servlet.FilterChain</li></ul>The object of this interface stores information about a chain of filters. <br />Void doFilter(ServletRequest request, ServletResponse response)           Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.<br />Container doesn’t call this method.<br />We have to call it explicitly.<br />chain.doFilter( request, response);<br />
    30. 30. How to apply a filter – In web.xml <br />Or <url-pattern>*</url-pattern> (in 2.5)<br /><servlet-name>/---Action</servlet-name><br /><filter><br /> <filter-name>LogFilter</filter-name> <br /> <filter-class>LogFilter</filter-class> <br /> <init-param><br /> <param-name>uname</param-name> <param-value>scott</param-value> <br /> </init-param> <br /></filter> <br /><filter-mapping> <br /> <filter-name>LogFilter</filter-name> <br /> <url-pattern>/####.jsp</url-pattern> <br /></filter-mapping><br />
    31. 31. What are the possible ways for a Servlet to get a request ?<br />Direct end-user request (REQUEST) (2.3 ver)<br />By RequestDispatcher forward (FORWARD)<br />By RequestDispatcher include (INCLUDE)<br />By error page call (ERROR)<br /> Java servlet 2.4 specification sun introduced <dispatcher> tag to extend filter concept for last 3 calls also.<br />
    32. 32. REQUEST – This is default value. Filter will only execute only on end user request.<br />FORWARD - Filter will only execute for RequestDispatcher forward calls.<br /><filter-mapping> <br /> <filter-name>LogFilter</filter-name> <br /> <url-pattern>*</url-pattern><br /> <dispatcher>REQUEST</dispatcher> <br /> <dispatcher>FORWARD</dispatcher><br /></filter-mapping><br />
    33. 33. INCLUDE – Filter will only execute for RequestDispatcher include calls.<br />ERROR - Filter will only execute for error page calls.<br /><filter-mapping> <br /> <filter-name>LogFilter</filter-name> <br /> <url-pattern>/report.jsp</url-pattern><br /> <dispatcher>ERROR</dispatcher><br /></filter-mapping><br /><error-page><br /> <exception-type>java.lang.ArithmeticException</exception-type><br /> <location>/index.jsp</location><br /></error-page><br />
    34. 34. In the context of web application there may be chances of occurring several events like – <br />Request object creation<br />Session object destruction<br />Context object creation <br />Adding attribute in request scope <br />Removing attribute from application scope etc..<br />Listeners<br />The servlet specification includes the capability to track key events in your Web applications through event listeners.<br />
    35. 35. Listeners are classified on the basis of event types.<br />Events can be of the request, session, application level scope.<br />The listener interfaces are in javax.servlet package : <br />Request Listeners : <br /><ul><li>ServletRequestListener
    36. 36. ServletRequestAttributeListener</li></ul>Context Listeners :<br /><ul><li>ServletContextListener
    37. 37. ServletContextAttributeListener</li></li></ul><li>3. Session listeners :<br /><ul><li>HttpSessionListener
    38. 38. HttpSessionAttributeListener
    39. 39. HttpSessionBindingListener
    40. 40. HttpSessionActivationListener</li></ul>ServletRequestListener :<br /> This listener listens lifecycle events of request object. It has two methods.<br /> void requestInitialized(ServletRequestEvent  rre) :<br /> This method will executed automatically at the time of request object creation i.e. before starting service method<br />
    41. 41. void requestDestroyed(ServletRequestEvent rre)<br /> This method will executed automatically at the time of request object destroyed.<br />ServletRequestAttributeListener :<br /> This listener listens events related to request scoped attributes. It has 3 methods.<br />void attributeAdded(ServletRequestAttributeEvent srae)<br />void attributeRemoved(ServletRequestAttributeEvent srae)<br />void attributeReplaced(ServletRequestAttributeEvent srae)<br />
    42. 42. ServletContextListener<br /><ul><li>void contextInitialized(ServletContextEvent sce)</li></ul> At the time of context object creation i.e. application deployment.<br /><ul><li>void contextDestroyed(ServletContextEvent sce)</li></ul>At the time application un deployment.<br />ServletContextAttributeListener : <br />void attributeAdded(ServletContextAttributeEventsrae)<br />void attributeRemoved(ServletContextAttributeEvent srae)<br />void attributeReplaced(ServletRequestAttributeEvent srae)<br />
    43. 43. HttpSessionListener : <br /> Related to life cycle of the session objects.<br />void sessionCreated(HttpSessionEvent se)<br />void sessionDestroyed(HttpSessionEvent se)<br />
    44. 44. public class Log4jListener implements ServletContextListener {<br />public void contextDestroyed(ServletContextEvent arg0) <br />{<br />}<br />public void contextInitialized(ServletContextEvent event) <br />{<br />String drive=System.getenv("HOMEDRIVE");<br />String separator=System.getProperty("file.separator");<br />String logfolder =drive+separator+"MyApps"+ separator+"logs"+ separator;<br />File file=new File(logfolder);<br />if(!file.exists())<br />file.mkdirs();<br />}}<br /><servlet><br /> <servlet-name>Log4jAction</servlet-name><br /> <servlet-class>com.eias.logging.Log4jAction </servlet-class><br /> <init-param><br /><param-name>log4j-properties-location</param-name><br /><param-value>WEB-INFproperties </param-value><br /></init-param> <br /> <load-on-startup>1</load-on-startup><br /> </servlet><br /><listener><br /> <listener-class>com.eias.logging.Log4jListener</listener-class><br /></listener><br />
    45. 45. wrapper<br />Whenever you want to create a custom request or response object, just subclass one of the convinces request or response “wrapper” classes.<br />A wrapper wraps the real request or response object, and passes through calls to the real thing, while still you do the extra things you need for your custom request or response.<br />The benefit of wrapping comes from custom coding a particular wrapping object to manipulate a request or response in a way not normally done.<br />
    46. 46. What are the core objects of servlet API ?<br />ServletRequest<br />ServletResponse<br />HttpServletRequest<br />HttpServletResponse<br />
    47. 47. ServletRequestWrapper<br />This class implements ServletRequest interface, <br />this class is further called by web developers to call their overridden methods.<br /> This class implements the Wrapper or Decorator pattern. <br /><ul><li>getAttribute( )           The default behavior of this method is to call getAttribute(String name) on the wrapped request object.
    48. 48. getRequest( )
    49. 49. getParameter( )
    50. 50. getParameterValues( )
    51. 51. setAttribute( )
    52. 52. removeAttribute( )</li></li></ul><li>ServletResponseWrapper<br />This class implements ServletResponse interface<br />getBufferSize() <br />Calls getBufferSize() response method on wrapped response object.<br />getResponse( ) <br />getWriter( )<br />setContentType( )<br />setContentLength( )<br />
    53. 53. Import javax.servlet.*;<br />Public class MyRequestWrapper extends ServletRequestWrapper{ <br />Public MyRequestWrapper (ServletRequestreq)<br />{<br />Super(req); <br />}<br />public String getParameter(String S) {<br />String s1=super.getParameter(s);<br />if(s1==null)<br /> s1=“ NONE ”;<br />return s1;<br />}<br />}<br />
    54. 54. Import javax.servlet.*;<br />Public class MyWrapperFilter implements Filter<br />{ <br />Public void init(FilterConfigfc) { } ;<br />Public void destroy() { } ;<br />Public void doFilter(ServletRequestreq, ServletResponse res, FilterChain chain) throws SE, IO … {<br />MyRequestWrapper wrapperReq= new MyRequestWrapper ();<br />Chian.doFilter(wrapperReq, res);<br />}<br />}<br />Wrapped request object <br />
    55. 55. Internationalization :<br />It can be defined as the process of enabling a web application to present different country and region specific formats without making any changes to the code or recompiling the application.<br />This term generally abbreviated as i18n. <br />Localization : This is a process of of customizing a software or web apps for a specific region or language.<br />Known as l10n<br />
    56. 56. locale: <br /> This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents English locale for US.<br />java.util.Locale class is used while creating international java application. <br />It is a non-abstract final class. <br />A Locale object represents a specific geographical, language, or cultural region locale.<br />These locale affect language choice, collation, calendar usage, date and time formats number and currency formats etc..<br />
    57. 57. Create a Locale object using the constructors in this class:<br />Locale(String language) <br />Locale(String language, String country)<br />Locale(String language, String country, String variant)<br />Ex – Locale myLocale=new Locale(“en”,”US”);<br />String getCountry()This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format.<br />
    58. 58. String getLanguage()This method returns the language code in lower case for this locale in ISO 639 format.<br /> String getVariant()           Returns the variant code for this locale.A ResourceBundle is like <br />a specialized form of a Hashtable that maps strings to values. <br />the magic of ResourceBundle allows you to have different lookup tables based upon what Locale (language/country) a user is coming in from.<br />
    59. 59. ResourceBundle class <br />This class is used to separate localizable elements such as button labels , error messages, and headings from rest of the application. <br />ResourceBundle "knows" how to search the hierarchy for a locale-appropriate instance,<br />getBundle(String baseName) <br />getBundle(String baseName, Locale locale) <br />This is a abstract class.<br />Two direct subclasses are :<br />PropertyResourceBundle - commonly used.<br />ListResourceBundle<br />
    60. 60. Resource bundle name have two parts <br />A base name <br />A suffix that defines specific locale.<br /><base name>_<lang>_<country> . Properties<br /><ul><li> - is the default
    61. 61.
    62. 62.</li></ul># Default properties in English<br />0=Zero:<br />1=One:<br />2=Two:<br />3=Three:<br />4=Four:<br />5=Five:<br />6=Six:<br />7=Seven:<br />8=Eight:<br />9=Nine:<br />10=Ten:<br /># Default properties in German<br />0=Null:<br />1=Eins:<br />2=Zwei:<br />3=Drei:<br />4=Vier:<br />5=Fünf:<br />6=Sechs:<br />7=Sieben:<br />8=Acht:<br />9=Neun:<br />10=Zehn:<br /># Default properties in French<br />0=Z:<br />1=Uun:<br />2=deux:<br />3=Trois:<br />4=Quatre:<br />5=cinq:<br />6=Six:<br />7=Sept:<br />8=Huit:<br />9=Neuf:<br />10=Dix:<br />random=au<br />
    63. 63. <key>=<value> in a property file having new line char as separator.<br />Message.prop<br />HELLO_MESSAGE= Hello, How r u ?<br />Message_ge.prop<br />HELLO_MESSAGE= Hallo, Wie geht es Ihnen??<br />Message_sp.prop<br />HELLO_MESSAGE= Hola, ¿Cómoestás?<br />
    64. 64. How to find out the user’s lang. preference.<br />2 ways<br />allow the user to choose language. Get it as request parameter.<br />It can use locale preferences that are sent from the client to the server using HTTP request header field Accept-Language. Use getLocale() . <br />Implementation in application :<br />Approach 1<br />Provide a version of JSPs page in each of the target locales and have the controller servlet dispatch the request to appropriate page. <br />Choose when large amount data is available on page. <br />Diadvantage is to create jsp pages for each locale.<br />
    65. 65. Approach 2 <br />Isolate the locale sensitive data on a page into resource bundles. (error message, labels, button values etc..) <br />Can be automatically retrieved from property file display in jsp.<br />Choose when less content.<br />Generally used.<br />example.jsp<br /><%@page import=“java.util.*”%><br /><% <br />ResourceBundle rb=<br />(ResourceBundle) request.getAttribute(“resourse”); <br />%><br /><%= rb.getString(“HELLO_MESSAGE”) %><br />
    66. 66. Public class I18NServlet extends HttpServlet<br />{<br />Public void service( req, response) throws SE, IO {<br />String cc=req,getParameter(“country”) ;<br />String lang=req,getParameter(“language”) ;<br />Locale l=null;<br />if(cc==null) <br /> l=new Locale(ln);<br />else<br /> l=new Locale(ln,cc);<br />ResourceBundle rb=<br />ResourceBundle.getBundle(“AppsResourse”,l); <br />req.setAttribute(“resource”,rb);<br />req.getRequestDispatcher(“example.jsp”).forward(req,res);<br />}<br />}<br />