Brief introduction to Filter filter in Java

  • 2020-06-12 08:54:40
  • OfStack

Filter profile

Filter, also known as filter, is the most useful technique in Servlet technology. Web developers use Filter technology to intercept all web resources managed by web server, such as Jsp, Servlet, static image files or static html files to achieve 1 special function. For example, URL level access control, filtering sensitive words, compression response information and other advanced functions.

It is mainly used for preprocessing user requests, but also for HttpServletResponse post-processing. The complete process with Filter: Filter preprocesses the user request, then sends the request to Servlet for processing and generating the response, and Filter post-processes the server response.

Filter function

Intercept the customer's HttpServletRequest before HttpServletRequest arrives at Servlet. Check HttpServletRequest as needed, or modify HttpServletRequest headers and data.

Intercept HttpServletResponse before HttpServletResponse reaches the client. Check HttpServletResponse as needed, or modify HttpServletResponse headers and data.

How to implement interception with Filter

There is one doFilter method in Filter interface. After the developer has written Filter and configured which web resource to intercept, the Web server will call the doFilter method under 1 before calling the service method of web resource every time. Therefore, writing code in this method can achieve the following goals:

Let 1 piece of code execute before invoking the target resource.

Whether the target resource is invoked (that is, whether the user is given access to the web resource).

web server when the call doFilter method, will deliver a filterChain object to come in, filterChain object is the most important one in filter interface object, it also provides a doFilter method, the developer can according to demand to decide whether to call this method, call the method, the web server is called web resources service method, namely web resources will be accessed, web resources will not be accessed.

Filter is a two-step development

Write the java class to implement the Filter interface and implement its doFilter method.

Register the filter class written in the web.xml file and set the resources it can intercept.

Configuration Of each node:

< filter > Specify 1 filter. < filter-name > Used to specify a name for a filter whose contents cannot be empty. < filter-class > The element is used to specify the full qualified class name of the filter. < init-param > The element is used to specify the initialization parameters for the filter, its child elements < param-name > Specify the name of the parameter, < param-value > Specifies the value of the parameter. In the filter, you can use the FilterConfig interface object to access the initialization parameters. < filter-mapping > The element is used to set a resource that Filter is responsible for intercepting. An Filter intercepted resource can be specified in two ways: the Servlet name and the request path for resource access < filter-name > The child element is used to set the registration name for filter. The value must be in < filter > The name of the filter declared in the element < url-pattern > Set the request path blocked by filter (the URL style associated with the filter) < servlet-name > Specifies the name of Servlet that the filter intercepts. < dispatcher > Specifies how the resource intercepted by the filter is invoked by the Servlet container, which can be REQUEST,INCLUDE,FORWARD and ERROR 1, default REQUEST. Users can set more than one < dispatcher > The child element is used to specify that Filter intercepts multiple calls to the resource. < dispatcher > The values and meanings that child elements can set REQUEST: When the user accesses the page directly, the Web container invokes the filter. This filter is not invoked if the target resource is accessed through RequestDispatcher's include() or forward() methods. INCLUDE: This filter is called if the target resource is accessed through RequestDispatcher's include() method. Otherwise, the filter is not invoked. FORWARD: If the target resource is accessed through RequestDispatcher's forward() method, then the filter will be called, otherwise the filter will not be called. ERROR: This filter is invoked if the target resource is invoked through a declarative exception handling mechanism. Otherwise, the filter is not invoked.

Filter chain

In one web application, it is possible to write multiple Filter, which together are called one Filter chain.

The web server decides which Filter to call first, based on the order in which Filter is registered in the ES173en.xml file. When the doFilter method of the first Filter is called, the web server creates an FilterChain object representing the Filter chain and passes it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server checks to see if filter is still in the FilterChain object, if so, the second filter, if not, the target resource.

The lifecycle of Filter


public void init(FilterConfig filterConfig) throws ServletException;// Initialize the 

Like the Servlet program 1 we wrote, the WEB server is responsible for the creation and destruction of Filter. When the web application starts, the web server creates an instance object of Filter and calls its init method, reads the ES202en.xml configuration, initializes the object, and prepares the block for subsequent user requests (the filter object is created only once, and the init method is executed only once). The developer gets the FilterConfig object that represents the current filter configuration information through the parameters of the init method.


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;// Intercept request

This method completes the actual filtering operation. When a customer requests access to the URL associated with the filter, the Servlet filter executes the doFilter method first. The FilterChain parameter is used to access subsequent filters.


public void destroy();// The destruction 

The Filter object is created, resides in memory, and is destroyed when the web application is removed or the server is stopped. Called before the Web container uninstalls the Filter object. This method is executed only once in the life cycle of Filter. In this method, you can release the resources used by the filter.

FilterConfig interface

When configuring filter, users can configure 1 of the filter initialization parameters. When the web container instantiates the Filter object and calls its init method, the filterConfig object that encapsulates the filter initialization parameters is passed in. So when a developer writes filter, using the method of the filterConfig object, he gets the following:


String getFilterName();// get filter The name of the.  
String getInitParameter(String name);// Returns the value of the initialization parameter named in the deployment description. If there is no return null. 
Enumeration getInitParameterNames();// Returns an enumerated collection of the names of all initialization parameters for the filter.  
public ServletContext getServletContext();// return Servlet A reference to a context object. 

Filter use cases

Verify user login security controls using Filter

Some time ago, I participated in the maintenance of one project. After users quit the system, they would go to the address bar to visit the history. According to url, they could still enter the system response page. I went to check 1 and found that the request was not filtered to verify the user's login. Add 1 filter to fix the problem!

First configuration in ES255en.xml


<filter>
  <filter-name>SessionFilter</filter-name>
  <filter-class>com.action.login.SessionFilter</filter-class>
  <init-param>
    <param-name>logonStrings</param-name><!--  The login page is not filtered  -->
    <param-value>/project/index.jsp;login.do</param-value>
  </init-param>
  <init-param>
    <param-name>includeStrings</param-name><!--  Filter only the specified filter parameter suffix  -->
    <param-value>.do;.jsp</param-value>
  </init-param>
  <init-param>
    <param-name>redirectPath</param-name><!--  Failed to jump to the login screen  -->
    <param-value>/index.jsp</param-value>
  </init-param>
  <init-param>
    <param-name>disabletestfilter</param-name><!-- Y: Filter is invalid  -->
    <param-value>N</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>SessionFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Then write FilterServlet


package com.action.login;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 *   Determine if the user is logged in , Log out of the system if you are not logged in 
 */
public class SessionFilter implements Filter {

  public FilterConfig config;

  public void destroy() {
    this.config = null;
  }

  public static boolean isContains(String container, String[] regx) {
    boolean result = false;

    for (int i = 0; i < regx.length; i++) {
      if (container.indexOf(regx[i]) != -1) {
        return true;
      }
    }
    return result;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hrequest = (HttpServletRequest)request;
    HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);

    String logonStrings = config.getInitParameter("logonStrings");    //  Login page 
    String includeStrings = config.getInitParameter("includeStrings");  //  Filter resource suffix parameters 
    String redirectPath = hrequest.getContextPath() + config.getInitParameter("redirectPath");//  No login to the redirect page 
    String disabletestfilter = config.getInitParameter("disabletestfilter");//  Whether the filter is effective 

    if (disabletestfilter.toUpperCase().equals("Y")) {  //  Filter is invalid 
      chain.doFilter(request, response);
      return;
    }
    String[] logonList = logonStrings.split(";");
    String[] includeList = includeStrings.split(";");

    if (!this.isContains(hrequest.getRequestURI(), includeList)) {//  Filter only the specified filter parameter suffix 
      chain.doFilter(request, response);
      return;
    }

    if (this.isContains(hrequest.getRequestURI(), logonList)) {//  The login page is not filtered 
      chain.doFilter(request, response);
      return;
    }

    String user = ( String ) hrequest.getSession().getAttribute("useronly");// Determine if the user is logged in 
    if (user == null) {
      wrapper.sendRedirect(redirectPath);
      return;
    }else {
      chain.doFilter(request, response);
      return;
    }
  }

  public void init(FilterConfig filterConfig) throws ServletException {
    config = filterConfig;
  }
}

This completes all requests to the user and authenticates the user login through the Filter.

Prevent Chinese scrambling filter

When projects use the spring framework. This filter can be used when different character sets are used in the current JSP page and Java code for encoding, and the data submitted in the form or the Chinese name file uploaded/downloaded is confused.


<filter>
  <filter-name>encoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name><!-- Used to specify 1 A specific character set -->
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
    <param-name>forceEncoding</param-name><!--true : no matter request Whether or not a character set is specified encoding ; false If: request Has been specified 1 Five character sets are not used encoding-->
    <param-value>false</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Related articles: