Monday, 7 September 2015

Filters

Filters:

·         Filter is a java program which provide the implementation of filter interface directly or indirectly
·         Filter is an object that performs the filtering tasks on either the request to a resource or response to resource.
·         Examples that have been identified for this design are
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Tokenizing Filters
7) Filters that trigger resource access events
8) XSL/T filters
9) Mime-type chain Filter 
·         Filter contains the following methods
o   init(FilterConfig config)
o   doFilter(ServletRequest request, ServletResponse response,    FilterChain chain)
o   destroy()
·         Procedure to create first application
o   Develop dynamic web module
o   Create filter class
public class MyFirstFilter implements Filter{
      FilterConfig config;
     
      public void init(FilterConfig config)     {
            this.config = config;
            System.out.println("init");
      }
     
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest requ = (HttpServletRequest)request;
            ServletContext application = requ.getServletContext();
            application.log("" + requ.getRemotePort());
            Enumeration<String> enu = requ.getHeaderNames();
            while (enu.hasMoreElements())       {
                  String s = enu.nextElement();
                  application.log(requ.getHeader(s));
            }
            chain.doFilter(request, response);
      }
     
      public void destroy()   {
            System.out.println("Destroy");
      }
}

o   Configure filter in web.xml file
<filter>
    <filter-name>firstFilter</filter-name>
    <filter-class>com.ibm.filter.MyFirstFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>firstFilter</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>

o   Deploy application
o   Access page from browser
·         Every request need to go to the filter so filters are import role in webapplications
·         Logging filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
                HttpServletRequest requ = (HttpServletRequest)request;
                ServletContext application = requ.getServletContext();
                application.log("" + requ.getRemotePort());
                Enumeration<String> enu = requ.getHeaderNames();
                while (enu.hasMoreElements()){
                                                String s = enu.nextElement();
                                                application.log(requ.getHeader(s));
                }
                chain.doFilter(request, response);
}


No comments:

Post a Comment