Filters are java classes that can dynamically intercept requests, manipulates them and manipulates response before sending it back to the client.
Sometimes, it may be necessary to do the same thing in different servlets. In those cases, a filter may be defined and reuse it for all of them.
Tasks that a filter can perform includes
To explain this concept, we shall create a servlet and two filters. Then we would see how can we call the first filter before the servlet is called, then the servlet and lastly the final filter would be called.
Code of servlet:
Sometimes, it may be necessary to do the same thing in different servlets. In those cases, a filter may be defined and reuse it for all of them.
Tasks that a filter can perform includes
- Authentication Filter
- Image Conversion
- Data Conversion
- Encryption
- Cache
To explain this concept, we shall create a servlet and two filters. Then we would see how can we call the first filter before the servlet is called, then the servlet and lastly the final filter would be called.
Code of servlet:
@WebServlet(name = "helloWorld", urlPatterns = "/helloWorld") public class helloWorld extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("This line is from servlet"); } }Then the code of first filter:
@WebFilter(filterName = "HelloAppenderFilter", urlPatterns = "/*") public class HelloAppenderFilter implements Filter { private FilterConfig filterConfig = null; public void destroy() { filterConfig = null; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { resp.getWriter().println("Hello (from filter 1)"); chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } }Second filter:
@WebFilter(filterName = "WorldAppenderFilter", urlPatterns = "/*") public class worldAppenderFilter implements Filter { private FilterConfig filterConfig; public void destroy() { filterConfig = null; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { chain.doFilter(req, resp); resp.getWriter().println("World (from filter 2)"); } public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } }If we check the url patterns of the both filters, we shall find no difference. Then how do we control the order of execution of these filters? Well, the answer lies in the web.xml file.
HelloAppenderFilter /* WorldAppenderFilter /*