To use Servlet interceptors, we need to use three interfaces: Filter, FilterChain, and FilterConfig

Let’s take a look at these interfaces

The Filter interface

By implementing the Filter interface, we can implement an interceptor to intercept the target request. A Filter is essentially a Java program that, like servlets, is called and executed by the Servlet container.

After we implement the interceptor, we register in web.xml and specify the requests to intercept. When a Servlet container calls a Servlet program and finds that a Filter program has been registered to intercept requests, the container does not directly call the Servlet program’s service method. Instead, it calls the Filter program’s doFilter method. It is up to the doFilter method to decide whether to call the service method.

The filter.dofilter method cannot call the Servlet’s service method directly, but instead calls the target Servlet’s service method by calling filterchain-dofilter (). The FilterChain object is passed as an argument to the doFilter method.

The java.servlet.Filter interface ** defines three methods: init, doFilter, destroy

  1. The init method

When the application starts, the Web container creates each registered Filter instance based on the web.xml configuration information and stores it in memory.

The init method is called when the container creates a Filter object. The init method is called only once in its lifetime. When the Web container calls the entire method, it passes a FilterConfig object containing the Filter configuration information and runtime environment information.

public voic init(FilterConfig filterConfig) throws ServletException
Copy the code
  1. DoFilter method

    When the target Servlet is requested, the Servlet first calls the doFilter method of Filter.

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException.ServletException
    Copy the code

    The parameters Request and Response are request and response objects passed by a Filter in the Web container. Chain represents the current Filter Chain object.

  2. destroy

    This method is called before the Web container unloads the Filter object and only once during the Filter’s lifetime. The Filter is used to release resources occupied by the Filter object, for example, closing database connections and I/O streams.

The Filter chain

There can be multiple filters intercepting the same request, thus forming a Filter chain. The order in which the individual filters in the Filter chain are intercepted is the order in which they are configured in the web.xml file.

The filterchain.dofilter method called by the previous filter.dofilter () method calls the next filter.dofilter method. The last filterchain. doFilter method calls the filterchain. doFilter method, which calls the service method of the target Servlet.

FilterChain interface

This interface is used to define the methods that a Filter chain object should provide. This interface defines only one doFilter method.

public void doFilter(ServletRequest request, ServletResponse response) throws java.io.IOException.ServletException
Copy the code

The doFilter method of the FilterChain interface is used to tell the Web container to pass the request to the next Filter in the Filter chain. If the current Filter object calling this method is the last Filter in the Filter chain, The request is handed over to the target Servlet for processing.

The FilterConfig interfaces

Like a Servlet program, a Filter program may also want to access the Servlet container. The Servlet specification encapsulates the parameter information representing both the ServletContext object and the Filter configuration into an object called FilterConfig.

The FilterConfig interface defines the methods that the FilterConfig object should provide so that these methods can be called in the Filter program to get the ServletContext object, as well as the name and initialization parameters configured for the Filter in the web.xml file.

The definition method is as follows:

  • The getFilterName method returns the value in the

    tag

  • The getServletContext method returns a reference to the ServletContext object wrapped in the FilterConfig object

  • The getInitParameter method returns the value of the initialized parameter for a name set for Filter in the web.xml file

  • The getInitParameterNames method returns an Enumeration collection object

Filter registration and mapping

registered

<filter>
  <filter-name>logFilter</filter-name>
  <filter-class>com.xgc.filter.LogFilter</filter-class>
  <init-param>
		<param-name>encoding</param-name>
        <param-value>utf-8</param-value>
  </init-param>
</filter>
Copy the code

mapping

There are two mapping modes of Filter: resource access request path and access request mode

Specify the resource access request path

<filter-mapping>
    <filter-name>logFilter</filter-name>
    <url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code

Interception of different request paths

In the web.xml file, each

element can be configured with a resource that a filter intercepts. There is a special child

in the

element that specifies how the resource intercepted by the filter is invoked by the Servlet container. Details are as follows:


  • The REQUEST (the default)

    When the user accesses the Servlet directly, the Web container invokes the filter. This filter will not be invoked if the target resource is accessed through the RequestDispatcher’s include or forward methods.

  • INCLUDE

    This filter is invoked if the target resource is accessed through the RequestDispatcher include method

  • FORWARD

    This filter is invoked if the target resource is accessed through the Forward method of the RequestDispatcher

  • ERROR

    This filter is invoked if the target resource is invoked through a declarative exception handling mechanism.

Using the example

View the project directory

LogFilter:

package com.xgc.filter;

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

public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Before the target Servlet's service method executes");
        chain.doFilter(request, response);
        System.out.println("After the target Servlet's service method executes"); }}Copy the code

TestServlet:

package com.xgc.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

public class TestServlet extends HttpServlet {

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("Processing requests"); }}Copy the code

web.xml

<? xml version="1.0" encoding="UTF-8"? > <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>testServlet</servlet-name>
        <servlet-class>com.xgc.servlet.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>testServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>logFilter</filter-name>
        <filter-class>com.xgc.filter.LogFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>logFilter</filter-name>
        <url-pattern>/test</url-pattern>
    </filter-mapping>
</web-app>
Copy the code

The project to run, the access path http://localhost:8080/javaweb/test

On the IDE console you’ll find the following output:

We can see that with interceptors we can do additional processing before and after the target Servlet’s Service method executes.

Refer to the article

Filter, FilterChain, FilterConfig