English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

A Brief Introduction to Filter in Java

Filter introduction

Filter is also known as a filter, which is the most practical technology in Servlet technology. Web developers use Filter technology to intercept all web resources managed by the web server: such as Jsp, Servlet, static image files, or static html files, and so on, thus realizing some special functions. For example, implementing URL-level access control, filtering sensitive words, compressing response information, and other advanced functions.

It is mainly used for pre-processing user requests and can also be used for post-processing of HttpServletResponse. The complete process of using Filter: The Filter pre-processes the user request, then passes the request to the Servlet for processing and generates a response, and finally the Filter performs post-processing on the server response.

Filter function

Intercept the client's HttpServletRequest before it reaches the Servlet. According to the need, check the HttpServletRequest, or modify the headers and data of the HttpServletRequest.

Intercept the HttpServletResponse before it reaches the client. According to the need, check the HttpServletResponse, or modify the headers and data of the HttpServletResponse.

How to implement intercepting functions with Filter

There is a doFilter method in the Filter interface. When developers have written a Filter and configured which web resource to intercept, the web server will call the filter's doFilter method before calling the service method of the web resource each time. Therefore, writing code in this method can achieve the following purposes:

Execute a piece of code before calling the target resource.

Whether to call the target resource (i.e., whether to allow users to access the web resource).

When the web server calls the doFilter method, it passes a filterChain object, which is the most important object in the filter interface. It also provides a doFilter method, and developers can decide whether to call this method according to their needs. If this method is called, the web server will call the service method of the web resource, that is, the web resource will be accessed; otherwise, the web resource will not be accessed.

Two steps to go for Filter development

Write a java class that implements the Filter interface and implements its doFilter method.

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

Introduction to each node of web.xml configuration:

  • <filter>specifies a filter.
  • <filter-name>is used to specify a name for the filter, the content of this element cannot be empty.
  • <filter-class>element is used to specify the complete qualified name of the filter.
  • <init-param>element is used to specify initialization parameters for the filter, with its sub-element <param-name>specifies the name of the parameter, <param-value>specifies the value of the parameter.
  • In the filter, the FilterConfig interface object can be used to access initialization parameters.
  • <filter-mapping>element is used to set the resource responsible for the filter. A resource intercepted by a filter can be specified in two ways: Servlet name and request path for resource access
  • <filter-name>sub-element is used to set the registration name of the filter. This value must be the name of a filter declared in the <filter> element
  • <url-pattern>sets the request path (URL pattern associated with the filter) that the filter intercepts.
  • <servlet-name>specifies the name of the Servlet intercepted by the filter.
  • <dispatcher> specifies the way in which the Servlet container invokes the resource intercepted by the filter, which can be one of REQUEST, INCLUDE, FORWARD, and ERROR, with the default being REQUEST. Users can set multiple <dispatcher> sub-elements to specify the various calling modes for the Filter to intercept resources.
  • The values and meanings that can be set for the <dispatcher> sub-element
  • REQUEST: The web container will invoke the filter when the user directly accesses the page. If the target resource is accessed via the include() or forward() method of RequestDispatcher, the filter will not be invoked.
  • INCLUDE: The filter will be invoked if the target resource is accessed via the include() method of RequestDispatcher. Otherwise, the filter will not be invoked.
  • FORWARD: If the target resource is accessed through the forward() method of RequestDispatcher, then this filter will be called. Otherwise, this filter will not be called.
  • ERROR: If the target resource is called through the declarative exception handling mechanism, then this filter will be called. Otherwise, the filter will not be called.

Filter chain

In a web application, multiple Filters can be developed and written. These Filters combined together are called a Filter chain.

The web server determines which Filter to call first based on the registration order of the Filter in the web.xml file. When the doFilter method of the first Filter is called, the web server will create a FilterChain object representing the Filter chain and pass it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there are still filters in the FilterChain object. If there are, the next filter will be called.2If there is no filter, the target resource is called.

The lifecycle of Filter

public void init(FilterConfig filterConfig) throws ServletException;//Initialization

Like the Servlet program we write, the creation and destruction of the Filter are handled by the WEB server. When the web application starts, the web server will create an instance of the Filter and call its init method to read the web.xml configuration, complete the initialization function of the object, and prepare for the interception of subsequent user requests (the filter object will only be created once, and the init method will only be executed once). Developers can obtain the FilterConfig object representing the current filter configuration through the parameters of the init method.

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

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

public void destroy();//Destroy

The Filter object will reside in memory after it is created. It will be destroyed only when the web application is removed or the server stops. This method is called before the Web container unloads the Filter object. This method is executed only once in the lifecycle of the Filter. In this method, you can release the resources used by the filter.

FilterConfig interface

When configuring the filter, the user can use some initialization parameters for the filter. When the web container instantiates the Filter object and calls its init method, it will pass in the filterConfig object encapsulating the filter initialization parameters. Therefore, developers can obtain the following content through the methods of the filterConfig object when writing the filter:

String getFilterName();//Get the name of the filter. 
String getInitParameter(String name);//Return the value of the initialization parameter specified by the name in the deployment description. If it does not exist, return null. 
Enumeration getInitParameterNames();//Return the enumeration collection of all names of the initialization parameters of the filter. 
public ServletContext getServletContext();//Return a reference to the ServletContext object.

Filter usage example

Use Filter to verify user login and implement security control

Recently, I participated in the maintenance of a project. After the user logs out of the system and accesses the history in the address bar, according to the URL, they can still enter the system response page. I checked and found that the request was not filtered and the user's login was not verified. Adding a filter solved the problem!

First, configure in web.xml

<filter>
  <filter-name>SessionFilter</filter-name>
  <filter-class>com.action.login.SessionFilter</filter-class>
  <init-param>
    <param-name>logonStrings</param-name><!-- Do not filter the login page -->
    <param-value>/project/index.jsp;login.do</param-value>
  </init-param>
  <init-param>
    <param-name>includeStrings</param-name><!-- Only filter the specified filter parameter suffix -->
    <param-value>.do;.jsp</param-value>
  </init-param>
  <init-param>
    <param-name>redirectPath</param-name><!-- Not passed, jump to the login interface -->
    <param-value>/index.jsp</param-value>
  </init-param>
  <init-param>
    <param-name>disabletestfilter</param-name><!-- Y: Filter invalid -->
    <param-value>N</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>SessionFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Next, 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 whether the user is logged in, and if not, exit the system
 */
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 to the login page
    String includeStrings = config.getInitParameter("includeStrings");  // Filter resource suffix parameters
    String redirectPath = hrequest.getContextPath() + config.getInitParameter("redirectPath");// No login redirect page
    String disabletestfilter = config.getInitParameter("disabletestfilter");// Is the filter valid
    if (disabletestfilter.toUpperCase().equals("Y")) {  // Filtering is invalid
      chain.doFilter(request, response);
      return;
    }
    String[] logonList = logonStrings.split(";");
    String[] includeList = includeStrings.split(";");
    if (!this.isContains(hrequest.getRequestURI(), includeList)) {// Only filter the specified filter parameter suffix
      chain.doFilter(request, response);
      return;
    }
    if (this.isContains(hrequest.getRequestURI(), logonList)) {// Do not filter the login page
      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 can complete the verification of all user requests, which must pass through this Filter to verify user login.

Prevent Chinese garbled code filter

When the project uses the spring framework. When the front-end JSP page and Java code use different character sets for encoding, it will cause form submission data or upload/If there is a problem with the乱码 of the Chinese name file during download, you can use this filter.

<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 a specific character set-->
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
    <param-name>forceEncoding</param-name><!--true: Use encoding regardless of whether the request specifies a character set; false: If the request has specified a character set, do not use encoding-->
    <param-value>false</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

That's all for this article. Hope it will be helpful to everyone's study, and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like