Web server filters

Available

Introduction to filters

But that's not all. You really don't think servlets are that simple, do you?

In addition to the servlets that we have already analyzed, there are also so-called “utility servlets” - filters . They are very similar to servlets, but their main job is to help servlets process requests.

A filter is like a secretary, and a servlet is like a director. Before the document reaches the director's desk, it will pass through the hands of the secretary. And after the director signs it, it will again go to the secretary, already as outgoing correspondence, for example.

Such a secretary can reject some of the requests to the director (for example, spam). Or give standard answers to questions known to him (“the director is not in place”). And so on. Moreover, there can be several such secretaries: one can filter spam for all directors at once, the other can transfer requests between different directors, and the like.

Filters work the same way.

Classes Filter, FilterChain, FilterConfig

Filters are very similar to servlets, but with a couple of small differences. To write your own filter, you need to inherit from the javax.servlet.Filter.

The filter also has methods init()and destroy(). Instead of a method, service()a filter has a doFilter(). And even has its own class FilterConfig. The filter is also added to the servlet in the web.xml file or via the @WebFilter annotation.

List of methods:

Methods Description
1 init(FilterConfig config) filter initialization
2 destroy() filter unloading
3 doFilter(ServletRequest , ServletResponse, FilterChain) request processing (filtering)

What is the difference between a servlet and a filter?

There can be several filters, and they sequentially process the request (and response). They are combined into a so-called chain - and there is even a special class for them FilterChain.

After processing the request in the method, doFilter()you need to call the method doFilter()of the next filter in the chain. Example:

public class MyFilter implements Filter {

  public void init(FilterConfig arg0) throws ServletException {
  }

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws Exception {

      PrintWriter out = resp.getWriter();
      out.print("Adding something before the body of the response");

      chain.doFilter(req, resp); // call the next filter in the chain

      out.print("Adding something after the body of the response");
    }

  public void destroy() {
  }
}

Actually, you can't add the response body like that . Formally, filters and servlets are independent of each other and can be changed independently. They can be written by different developers at different times. The filter function is just a service function, for example:

  • Logging all incoming requests (and responses)
  • Data compression
  • Encryption (and decryption) of data
  • Request Data Validation
  • Add/remove desired headers
  • Redirect requests
  • Access control (checking if the user is logged in)

RequestDispatcher class

doFilter() Sometimes it may be necessary to call another servlet while a filter is running within a method . To do this, the container has a special object RequestDispatcher.

You can get it in two ways:

  • At the objectHttpServletRequest
  • At the objectServletContext

This object can be used to redirect an existing request to another servlet . For example, it turned out that the user is not authorized and we want to show him a page with authorization. Well, or there was an error on the server and we want to display an error page to the user :)

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws Exception {
           String path = "/error.html";
           ServletContext servletContext = this.getServletContext();
           RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(path);
           requestDispatcher.forward(request, response);
    }
}

You can also call RequestDispatcherfrom a filter.

public class MyFilter implements Filter {

  public void init(FilterConfig arg0) throws ServletException {
  }

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws Exception {
           String path = "/error.html";
           ServletContext servletContext = req.getServletContext();
           RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(path);
           requestDispatcher.forward(req, resp);
    }

  public void destroy() {
  }
}

Note that the request will be handled in the method forward()and there is no need to call doFilter()after use RequestDispatcher.

Comparison of redirect and forward

And one more important point. If you want to redirect the user to another URI in your servlet, then you can do this in two ways:

  • redirect
  • forward

We have already analyzed them, but for convenience I will say it again.

When you redirect via a call response.sendRedirect("link"), the server sends back to the browser (client) a response 302and the link you specified. And the browser, after analyzing the server response, downloads the link you passed. That is, the link in the browser changes to a new one.

If you forward via a call requestDispatcher.forward(), then a new request is made inside the container, and your servlet sends its response to the browser (client) as your servlet's response. In this case, the browser receives a response from the new servlet, but the link in the browser does not change.

Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet