Search This Blog


Filter is interface in Java which will be execute before servlet execution ,Filter will work as a intermediate from request object to Servlet Object.

If we want to apply authentication or Security before servlet response then we can use Filter Under Servlet.

Filter always will be created from particular Servlet class.


Filter Interface contain three different methods

1 init  ---->  It is used to initialize data member etc.

2 doFilter()----> Write Logical Code under this method

3 destroy() ---->  it is used to destroy object or reset values.


Web.xml file use following tag to map with Servlet Class:-

 <filter>
        <filter-name>FilterExample</filter-name>
        <filter-class>FilterExample</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterExample</filter-name>
        <servlet-name>Servlet1</servlet-name>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>





/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author DELL
 */
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
     
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
     PrintWriter out=response.getWriter(); 
    out.print("<script>alert('hello');</script>"); 
         
    chain.doFilter(request, response);//sends request to next resource 
         
    out.print("filter is invoked after"); 
    }

    @Override
    public void destroy() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
   
 
   
}


web.xml

<filter>
        <filter-name>FileterDemo</filter-name>
        <filter-class>FileterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FileterDemo</filter-name>
        <url-pattern>/Servlet2</url-pattern>
    </filter-mapping>



Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post