JavaWeb-Filter filter

Table of contents

Filter

1. Filter life cycle

2.Filter configuration

3. Intercept path

4. Intercept specific usage

 5. Interception method configuration (resource access method)

6.FilterChain interception chain


Filter

      Filter is a filter, compared to Servlet sending requests, filter is used to intercept requests. For example, in the login system, users who log in normally can access the relevant resources of the server, and if the login information is wrong, the request to access the resource is intercepted. The following will introduce the filter in detail

1. Filter life cycle

The life cycle of Filter is divided into three parts, namely init() initialization; doFilter() execution interception; destroy() destruction;

The specific code is as follows

package com.company.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//注解配置实现所有请求访问都进行拦截
@WebFilter("/*")
public class filterDemo1 implements Filter {
//    初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("加载的时候自动执行,并且只执行一次");
    }
//    执行拦截
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("实现拦截的时候执行函数,可以多次执行");
    }
//    销毁
    @Override
    public void destroy() {
        System.out.println("在服务器关闭的时候,执行销毁函数");
    }
}

2.Filter configuration

Filter configuration is divided into two types, one is xml configuration, and the other is through annotation class configuration

  • Configuration via xml (open web.xml):
    <filter>
<!--        随便创建想要的名称-->
        <filter-name>filterDemo1</filter-name>
<!--        filter对应的具体类-->
        <filter-class>com.company.Filter.filterDemo1</filter-class>
    </filter>
<!--    创建filter对应的映射-->
    <filter-mapping>
<!--        filter对应的名称-->
        <filter-name>filterDemo1</filter-name>
<!--        拦截路径,/*表示所有访问都会进行拦截-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • Configure through annotation classes:

@WebFilter(value=url-pattern)

If you only need to write the interception path, you can omit value =;

Directly input @WebFilter("/*") to intercept all access to data


3. Intercept path

I just introduced that /* is the interception of all requests, but the interception of specific access requests cannot be achieved. The following introduces other interception paths

  1. Interception of specific path access: /index.jsp (interception is realized when accessing the index.jsp file)
  2. Interception of access to a certain directory: /user (intercept when accessing all files under the user directory)
  3. Interception of suffix access: *.jsp (to intercept access to all files ending with .jsp suffix)
  4. Intercept all related paths: /* (Intercept is implemented when accessing all server resources)

4. Intercept specific usage

1. Create a class to implement the Filter interface (note that the Filter interface is in the package javax.servlet)

2. Override the life cycle function

3. Implement interception through the doFilter function. release after passing

Case code:

interception class

package com.company.Filter;

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

//通过注解类实现拦截路径
@WebFilter("/*")
//实现接口
public class filterDemo2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器已被加载");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("发现请求,实施拦截");
       进行验证,如果通过则实现放行
//        System.out.println("验证成功,放行");
//        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("服务器关闭时候执行销毁函数");
    }
}

Mock resource class

package com.company;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/FilterDemo3")
public class FilterDemo3 extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("访问到资源啦");
    }
//    方法统一
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

When accessing the resource class through url, you can see that the request is intercepted, and the output of "access resource class" cannot be executed in the resource class.

After adding the verification function, if it is allowed to pass, it needs to be released. Execute the doFilter (servletRequest object, servletResponse object) of the filterChain object in FilterChain filterChain, that is, the code

//        拦截结束后如果通过则实现放行
        System.out.println("验证成功,放行");
        filterChain.doFilter(servletRequest, servletResponse);

 At this time, after accessing through the url, you can see the console information:


 5. Interception method configuration (resource access method)

Of course, in addition to intercepting path access, you can also set the interception method. Some requests can directly enter the url to directly access the class. Some obtain class resources by means of some web pages to achieve jumps. Another is to obtain the class through the form of request forwarding. So based on this, some restrictions can be made on these methods.

Intercept method describe
REQUEST (request interception) Intercept requests accessed directly through URLs.
FOWARD (forward interception) Intercept requests to obtain resources through request forwarding.
INCLUDE (including interception) Intercept requests to obtain resources through web page jumps.
ERROR (error interception) Intercept requests where errors or unusual conditions occur.
ASYNC (asynchronous interception) Intercepting asynchronous requests, i.e. lazy loaded requests, prevents responses from being precached and used.

By default, interception is implemented through REQUEST

The specific use depends on the configuration used at the beginning

  • Configuration via xml
   <filter>
        <filter-name>filterDemo1</filter-name>
        <filter-class>com.company.Filter.filterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filterDemo1</filter-name>
        <url-pattern>/*</url-pattern>
<!--        配置请求拦截方法-->
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
  • Configuration via annotation class


6.FilterChain interception chain

The interception chain, as the name implies, is composed of multiple filters, just like a road with multiple tollbooths. Pass only if all blocking rules are met.

Set up multiple interceptors (code for one of them)

package com.company.Filter;

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

@WebFilter("/*")
public class filterDemo3 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截器1进行拦截");
        System.out.println("拦截器1放行");
//        拦截器放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {

    }
}

When accessing through url, the result is as follows

 order of interceptors

1. Annotation configuration

It is through the sorting of interceptor names such as 01, 02, 03, first compare the size of the first number, if they are the same, compare the size of the second number, and so on

Two.xml configuration

You only need to configure xml from top to bottom


next post

JavaWeb-Listener listener_Alphamilk's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132289924