[Twenty] springboot integration filter combat

        In the project development process, filters or interceptors are almost necessary. They can easily complete a series of operations such as log processing and token verification. Different from business interfaces, they can be processed independently. It feels like an Aop idea. The following simulates the token verification before the request interface, and performs the actual combat of the filter .

Qq exchange group navigation ——> 231378628

 The overall column of the springboot chapter: 


[1] springboot integrates swagger (super detailed

[2] springboot integrates swagger (custom) (super detailed)

[3] springboot integration token (super detailed)

[4] springboot integrates mybatis-plus (super detailed) (on)

[5] springboot integrates mybatis-plus (super detailed) (below)

[6] springboot integrates custom global exception handling

[7] springboot integrates redis (super detailed)

[8] springboot integrates AOP to realize log operation (super detailed)

[Nine] springboot integrated timing tasks (super detailed)

[10] springboot integrates redis to realize the startup service, that is, save the hotspot data in the global and redis (super detailed)

[Eleven] springboot integrates quartz to realize timing task optimization (super detailed)

[Twelve] springboot integrates thread pool to solve high concurrency (super detailed, keep you understanding)

[Thirteen] springboot integrates asynchronous calls and obtains return values ​​(super detailed)

[14] springboot integrates WebService (super detailed)

[Fifteen] springboot integrates WebService (about passing parameters) (super detailed)

[16] springboot integrates WebSocket (super detailed)

[Seventeen] springboot integrates WebSocket to realize chat room (super detailed)

[Eighteen] springboot implements custom global exception handling

[Nineteen] springboot integrates ElasticSearch actual combat (ten thousand characters)

[Twenty] springboot integration filter combat

[21] springboot integrates interceptors in actual combat and compares filters

[22] springboot integration activiti7 (1) practical demonstration

【23】springboot integrated spring business detailed explanation and actual combat

[24] springboot uses EasyExcel and thread pool to realize multi-threaded import of Excel data

[25] springboot integrates jedis and redisson Bloom filters to handle cache penetration

[26] springboot implements multi-threaded transaction processing_springboot multi-threaded transaction

[27] springboot realizes the function of saving the current login information like the session through the threadLocal+ parameter parser


Table of contents

1. Ordinary interface access

2. Add a filter

3. Add two filters


        Let's first create a basic request interface of MVC, as follows:

1. Ordinary interface access

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

                As above, first add a testController.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

        First use postman to test whether it works.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

        The result is passable, and the preparations are complete.

2. Add a filter

        Add a filter below to implement an interface interception and handle token verification simulation.

        Simple processing has the following two steps.

        1. Custom filter

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

package com.example.demo_filter_interceptor.config;

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

/**
 * @Classname TestFilter
 * @Description TODO
 * @Date 2022/4/11 19:30
 * @Created by zrc
 */
//实现Filter接口,基于回调的方式,类似ajax请求的success。
public class TestFilter implements Filter {

    //init方法,初始化过滤器,可以在init()方法中完成与构造方法类似的初始化功能,
    //如果初始化代码中要使用到FillerConfig对象,那么这些初始化代码就只能在Filler的init()方法中编写而不能在构造方法中编写
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("第一个过滤器成功初始化。。。。。。。。。。。。。");
    }

    //doFilter()方法有多个参数,其中
    //参数request和response为Web服务器或Filter链中的上一个Filter传递过来的请求和响应对象;
    //参数chain代表当前Filter链的对象,
    //只有在当前Filter对象中的doFilter()方法内部需要调用FilterChain对象的doFilter()法才能把请求交付给Filter链中的下一个Filter或者目标程序处理
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //这里为了使用getHeader方法获取token,转型成HttpServletRequest
        System.out.println("token:"+req.getHeader("token"));
        String token = req.getHeader("token");
        //再判断token是否正确
        if(null==token){
            throw new RuntimeException("token为空");
        }
        //调用doFilter方法,正常返回servletResponse
        filterChain.doFilter(servletRequest, servletResponse);
    }

    //destroy()方法在Web服务器卸载Filter对象之前被调用,该方法用于释放被Filter对象打开的资源,例如关闭数据库和I/O流
    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("过滤器被销毁");
    }
}

        Implement the Filter interface of the servlet, and rewrite its three methods , namely init, doFilter, and destroy.

  • init: Callback when the filter is initialized. You can perform filter initialization operations here, such as setting the whitelist path list.
  • doFilter: Callback after the filter is initialized and when the request reaches the backend and enters the matching path set by the registered filter.
  • destroy: callback when the filter is destroyed.

        The above figure is a simple way to check whether the token is empty or not, without checking whether it is correct or not, you can introduce redis (mentioned in the previous chapter) or other storage, and then perform a correctness check. Get the token header from the request, if it exists, call the doFilter method ( through the filter ), otherwise do not operate (that is, if it does not pass the filter , it will not reach the controller).

        2. Register to the container

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

@Configuration
public class TestFilterConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        //创建一个注册过滤器对象
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //设置自定义过滤器
        registrationBean.setFilter(new TestFilter());
        //设置过滤拦截匹配规则,/*是匹配所有
//        registrationBean.addUrlPatterns("/*");
        //只拦截testController下面的接口
        registrationBean.addUrlPatterns("/testController/*");
        //存在多个过滤器时,设置执行顺序,值越大,执行顺序越靠后
        registrationBean.setOrder(2);
        //返回这个注册过滤器对象
        return registrationBean;
    }

}

        Register the custom filter in the container, and set the parameters of the filter through a series of methods of FilterRegistrationBean, such as the path to be filtered, the priority of the filter , and so on.

        3. Demonstrate the effect:

        Without token:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

        带token:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

3. Add two filters

        Next, when there are multiple filters, how to set which filter to intercept first and which one to execute later (priority).

        As in the second section, make another custom filter.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

package com.example.demo_filter_interceptor.config;

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

/**
 * @Classname TestFilter
 * @Description TODO
 * @Date 2022/4/11 19:30
 * @Created by zrc
 */
//实现Filter接口,基于回调的方式,类似ajax请求的success。
public class TestFilter2 implements Filter {

    //init方法,初始化过滤器,可以在init()方法中完成与构造方法类似的初始化功能,
    //如果初始化代码中要使用到FillerConfig对象,那么这些初始化代码就只能在Filler的init()方法中编写而不能在构造方法中编写
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("第二个过滤器成功初始化。。。。。。。。。。。。。");
    }

    //doFilter()方法有多个参数,其中
    //参数request和response为Web服务器或Filter链中的上一个Filter传递过来的请求和响应对象;
    //参数chain代表当前Filter链的对象,
    //只有在当前Filter对象中的doFilter()方法内部需要调用FilterChain对象的doFilter()法才能把请求交付给Filter链中的下一个Filter或者目标程序处理
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("这里是第一顺序的拦截器");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    //destroy()方法在Web服务器卸载Filter对象之前被调用,该方法用于释放被Filter对象打开的资源,例如关闭数据库和I/O流
    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("过滤器被销毁");
    }
}

        Modify the class that registers the filter.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

        Similar to the registration of the first filter, just register a second filter. Different interception paths can be set, each responsible for its own logic processing. Here we only demonstrate the execution order problem. The first setting of the Order parameter is 2. The second one is set to 1, and the bigger one is executed later. After setting, test it with postman.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bCPeuKZgA==,size_20,color_FFFFFF,t_70,g_se,x_16

        After calling the interface, it is found that the doFilter method of the first filter is entered first, and then the doFilter method of the second filter is entered to verify that the order parameter is valid.

Supongo que te gusta

Origin blog.csdn.net/weixin_56995925/article/details/124108429
Recomendado
Clasificación