Servlets - filter, listeners, wrapper, internationalization

  • 3,838 views
Uploaded on

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

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

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
3,838
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
144
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    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?

Transcript

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