Saturday, 23 August 2014

addFilter (String filterName, Class filterClass)

public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass)
Adds the filter with the given name and class type to this servlet context.

import java.io.*;
import javax.servlet.*;

public class Filter1 implements Filter {
    
     @Override
   public void init(FilterConfig filterConfig) throws ServletException{
       
   }
   
   @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
        System.out.println("Filter Added to the Application");
        chain.doFilter(req, res);
    }
    
   @Override
    public void destroy(){
        
    }
}

import javax.servlet.*;

public class NewServletListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        FilterRegistration.Dynamic addFilter = context.addFilter("Filter1", Filter1.class);
   
        /* Adding URL Pattern to the filters */
        addFilter.addMappingForUrlPatterns(null, true, "/*");
   }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/ServletEx"})
public class ServletEx extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
        try(PrintWriter out = res.getWriter()){
            out.println("Hiiii");
        }
    }
}

Run the above Servlet Application, and you can see the message 'Filter Added to the Application' in the console.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment