Filter for Java Web

Keywords: Java

Filter for Java Web

1. What is a Filter

Filter filter, as the name suggests, is used to filter. What is it? In Java Web, the client accesses the resources in the server through the address, such as html page, jsp page, txt file, audio, video, picture and so on. However, we sometimes do not want all requests to access these resources on the server. We hope that this access is conditional and constrained. For example, we hope that only the logged in user can see some pages of the web page, while the non logged in user does not want him to see them. At this time, we need to use the filter.

2. Why use Filter

Consider such a scenario. The back end of a website saves the user's login information to the Session domain after the user logs in. At this time, we have a requirement to intercept the user's request to access the resource target.jsp when the user does not log in. Let's take a look. The first thing we can think of is that since the user logs in and the information is saved to the Session domain, we can judge whether the user logs in by checking whether there is user information in the Session domain, and then intercept the request. At this time, we directly go to the location of the request target.jsp (it may be a button or a hyperlink label, which we can judge in the click event method) to judge, there is the following code

User user = session.getAttribute("user");
request.getRequestDispatcher("Address of landing page").forward(request,response);

Imagine if there are many such pages that need to judge whether they can be accessed, and we still judge in this way, it will inevitably lead to code redundancy and maintenance difficulties, and the Filter filter can easily complete such tasks.

3. How to use Filter

Before using Filter, let's take a look at a picture to better understand Filter (the client is actually the browser)

The specified page here is actually the page we can customize to jump to when the conditions are not met in the filter.
Filter is an interface. We need to create a class to implement this interface and implement the methods in the interface. We need to focus on these three methods

//Initialization method, which is executed when the project is started
void init()
//This method is the key point, in which the filter conditions are written
void doFilter()
//The destruction method shall be implemented at the end of the project
void destroy()

Now let's create the MyFilter class to implement this interface

//Remember to guide the bag!!
public class MyFilter implements Filter {
    public void init() {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filter) {
        //In this method, we migrate the code we wrote before
        //First, get the session. The type conversion here is because servletRequset has no getSession() method
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("user") == null) {
            //Request forwarding
            servletRequest.getRequsetDispacher("Path to jump to").forward(servletRequset, servletResponse);
        } else {
            //This code can be understood as that the Filter is released and the request continues to move in the direction of the server. The FilterChain will be explained later
            filterChain.doFilter(servletRequset, servletResponse);


    public void destory() {

Just writing the implementation class and filter method of the interface can not intercept the request. We need to configure the filter and intercept address in the web.xml configuration file as the last step

        <!--Here is the full class name-->
        <!--The interception path is configured here,Write path from project name-->

After the above steps, a basic Filter is written. This Filter can help us intercept the request for the address in the configuration file and decide whether to release the request according to the conditions we have written.

4. Go deep into Filter

After understanding the third simple use of filters, let's think again. Sometimes we actually write multiple filters. What is the relationship between these filters and servers and clients, and how they are connected together? Here I'll tell you the answer: servers, filters and clients are connected through FilterChain. Let's start Look at this diagram.

At first glance, it doesn't seem a little confused. Don't worry. I'll tell you the meaning of abc in the figure first, and you will suddenly see the light. First, this figure describes such a process: client (browser) A resource on the server is requested. In the middle, we set two filters. All these filters release the request. Finally, the server responds to the request of the client. As we have said above, the request that is intercepted on a filter is forwarded to other places. We will not discuss it here. The meaning of abc: We It is actually the doFilter method that knows that the filter really plays a role in filtering. A represents the code before the filterChain.doFilter method in the doFilter method, c represents the code after the filterChain.doFilter method in the doFilter method, and b represents the filterChain.doFilter method. This figure is very clear: I can describe this figure in this way - one that passes through multiple filters and has no filter If there are filtered requests, first go through a and b in Filter1, then a and b in Filter2, and then arrive at the server. The server responds to the client. At this time, the client can see the requested resources, then c in Filter2 is executed, and then c in Filter1 is executed. The white number in the figure indicates the execution order! Then the next problem comes when there are multiple requests What is the order in which requests pass through the filter when there are two filters? The answer is simple: it depends on the order in which you configure the filter in web.xml!

Posted by fatepower on Sun, 24 Oct 2021 05:36:48 -0700