Servlet Filter Interview questions - Tech Interview Club

Latest

interview questions for java,spring,servlet,jsp,hibernate,webservices,.net,html,javascript,andriod,jquery

Comments

Saturday, 24 June 2017

Servlet Filter Interview questions

1.What is  filters?

It is mainly used to perform filtering tasks such as 
·      recording all incoming requests
·      logs the IP addresses of the computers from which the requests originate
·      conversion
·      data compression
·      encryption and decryption
·      Input validation etc.
Advantages of filters:
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. So maintenance cost will be less.One filter doesn’t have dependency onto another resource.

2.Explain About Filter API?
 1. Servlet filter is a java program that implements javax.servlet. Filterinterface.
2. Filters have its own API the javax.servlet package contains the three interfaces of Filter API.
1.    Filter
2.    Filter Chain
3.    FilterConfig
3. Every servlet Filter Program configure in web.xml file using filter tag.
4. To link servlet filter program with servlet program of web application the URL pattern of servlet program must be taken as URL pattern of servlet filter program.
5. Servlet container creates our servlet filter class object during server startup or deployment of web application.
6. We can map servlet filter program with one servlet program or multiple servlet programs or all servlet programs of web application.

1) Filter interface

For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.
Method
Description
public void init(FilterConfigconfig)
Init () method is invoked only once. It is used to initialize the filter.
public void doFilter(HttpServletRequestrequest,HttpServletResponse response, FilterChain chain)
doFilter () method is invoked every time when user request to any resource, to which the filter is mapped. It is used to perform filtering tasks.
public void destroy()
This is invoked only once when filter is taken out of the service.

2) Filter Chain interface

The object of FilterChain is responsible to invoke the next filter or resource in the chain. This object is passed in the doFilter method of Filter interface. The FilterChain interface contains only one method:
1.    Public void doFilter (HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.

3) FilterConfig

An object of FilterConfig is created by the web container. This object can be used to get the configuration information and get init parameters values of filter program from the web.xml file.

Methods of FilterConfig interface

There are following 4 methods in the FilterConfig interface.
1.    public void init (FilterConfigconfig): init () method is invoked only once it is used to initialize the filter.
2.    public String getInitParameter (String parameterName): Returns the parameter value for the specified parameter name.
3.    publicjava.util.EnumerationgetInitParameterNames (): Returns an enumeration containing all the parameter names.
4.    public ServletContext getServletContext (): Returns the ServletContext object.

7.There are three types of filter programming.
    1. Request Filter (contains only pre request processing logic ex: Authentication, authorization filters)
    2. Response Filter (contains only post response generation logic ex: compression filter)
    3. Request and response filter (contains both pre request processing, post response    generation ex: performance monitoring filter)


3.Example of counting number of visitors for a single page?

MyFilter.java
import java.io.*;  
import javax.servlet.*;  
  
public class MyFilter implements Filter {  
    static int count=0;  
    public void init (FilterConfig arg0) throws ServletException {}  
  
    public void doFilter (ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
      
        PrintWriter out=res.getWriter ();  
        chain.doFilter (request, response);  
          
        out.print ("<br/>Total visitors "+ (++count));  
        out.close ();  
          
    }  
    public void destroy () {}  
}  
4.Example of checking total response time in filter?

MyFilter.java
import java.io.*;  
import javax.servlet.*;  
  
public class MyFilter implements Filter {  
    Static int count=0;  
    public void init (FilterConfig arg0) throws ServletException {}  
  
    public void doFilter (ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
      
        PrintWriter out=res.getWriter ();  
        long before=System.currentTimeMillis ();  
  
        chain.doFilter (request, response);  
          
        long after=System.currentTimeMillis ();  
        out.print ("<br/>Total response time "+(after-before)+" milliseconds");  
        Out. Close ();  
          
    }  
    public void destroy () {}  
}  

5.What is the difference between the dofilter () method of javax.servlet.filter and dofilter () method of javax.servlet.chainfilter?

Dofilter() method of filter interface is life cycle method of servlet filter program so programmer uses this method to place pre request  processing and post response generation  logic.
Dofilter () method of filter chain interface is not a life cycle method  so programmer uses this method to invoke  next filter in the chain to mapped  servlet or jsp program.

6.What is the effective way to make sure all the servlets are accessible only when user has a valid session?

We know that servlet filters can be used to intercept request between servlet container and servlet, we can utilize it to create authentication filter and check if request contains a valid session or not.

No comments:

Post a Comment