SpringBoot (fourteen) filter

1. Filter

1. Filter Introduction

Interceptor (Interceptor) is the same as Filter filter, both of them are aspect-oriented programming - the specific implementation of AOP (AOP aspect programming is just a programming idea).

The English name of the filter is Filter, which is the most practical technology in Servlet technology. Just like its name, a filter is a filter between the client and server resource files, which helps us filter some requests that do not meet the requirements. Usually it is used as Session verification to judge user permissions, if it does not meet the set conditions, it will be intercepted to a special address or given a special response. To implement the Filter interface

2. Filter life cycle

Using a filter is very simple, you only need to implement the Filter class, and then rewrite its three methods.

init method: the program starts to call the init() method of Filter (only called once); this method is automatically called when the current filter is created in the container.

destroy method: The program stops calling the destroy() method of Filter (it is called only once forever); this method is automatically called when the current filter is destroyed in the container.

doFilter method: the doFilter() method will be called every time the access request meets the interception conditions (the first time the program runs, it will be called after the servlet calls the init() method; no matter how many times, it is calling doGet(), doPost( ) method before). This method has three parameters, which are ServletRequest, ServletResponse and FilterChain. HttpServletReguest and HttpServletResponse objects can be obtained from the parameters for corresponding processing operations.

3. Annotation way to implement filter (@WebFilter)

@WebFilter

@WebFilter is used to declare a class as a filter, the annotation will be processed by the container during deployment, and the container will deploy the corresponding class as a filter according to the specific attribute configuration. This annotation has some common attributes given in the following table (all the following attributes are optional attributes, but value, urlPatterns, and servletNames must contain at least one, and value and urlPatterns cannot coexist. If specified at the same time, the selection of value is usually ignored value)

@Order(1)

Identifies the execution order of the current filter, the smaller the value, the higher the execution, the priority of the annotation is higher than the priority of the configuration class

@ServletComponentScan

The @WebFilter annotation will take effect only when the annotation is added to the springboot startup class. The @WebFilter annotation will take effect after the @ServletComponentScan annotation is used on SpringBootApplication

Servlets can be automatically registered directly through the @WebServlet annotation. Filters can be automatically registered directly through the @WebFilter annotation. Listeners can be automatically registered directly through the @WebListener annotation.

Startup class code

@SpringBootApplication
@ServletComponentScan//开启filter过滤器,添加该注解时@WebFilter注解才会生效
public class ApplicationStarter {
  public static void main(String[] args) {
      SpringApplication.run(ApplicationStarter.class,args);
  }
}

4. Use annotation Filter filter code

Implement Filter

/**
 * @ClassName:TokenFilter
 * @Auther: YooAo
 * @Description: 注解配置过滤器  @WebFilter(urlPatterns = "/test/*", filterName = "testFilter")
 * @Date: 2023/4/5 09:30
 * @Version: v1.0
 */
//urlPatterns:拦截器路径,filterName:就是设置一个名字,不设置名字
@WebFilter(urlPatterns = "/test/*", filterName = "testFilter")
@Order(1)//设置优先级,优先级越高执行顺序就越高,注解的优先级比配置类的优先级要高
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Filter.super.init(filterConfig);
        System.out.println("int1----");
    }
​
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter1");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");//获取请求头
        System.out.println("token");
        //该方法执行后直接运行至下一个过滤器
        if(token!=null){
            filterChain.doFilter(servletRequest, servletResponse);// 直接放行
        }else{
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = servletResponse.getWriter();
            JSONObject res = new JSONObject();
            res.put("msg", "错误");
            res.put("success", "false");
            out.append(res.toString());
        }
    }
​
    @Override
    public void destroy() {
//        Filter.super.destroy();
        System.out.println("destroy1-----");
    }
}

5. Use configuration classes to inject directly into spring

Filter configuration class code

/**
 * @ClassName:FilterConfig
 * @Auther: YooAo
 * @Description: 过滤器配置类
 * @Date: 2023/4/5 09:54
 * @Version: v1.0
 */
@Configuration
public class FilterConfig {
​
    //装配TokenFilter2过滤器
    @Bean
    public TokenFilter2 myFilter() {
        return new TokenFilter2();
    }
​
    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(TokenFilter2 myFilter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(myFilter);//设置过滤器类
        filterRegistrationBean.setOrder(2);//设置优先级,优先级越高执行顺序就越高,注解的优先级比配置类的优先级要高
        filterRegistrationBean.addUrlPatterns("/test/*");
        filterRegistrationBean.setName("myFilter");
        return filterRegistrationBean;
    }
​
}

Filter code

/**
 * @ClassName:TokenFilter
 * @Auther: YooAo
 * @Description: 配置类配置过滤器
 * @Date: 2023/4/5 09:30
 * @Version: v1.0
 */
​
public class TokenFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Filter.super.init(filterConfig);
        System.out.println("int2----");
    }
​
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter2");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");//获取请求头
        System.out.println("token");
        //该方法执行后直接运行至下一个过滤器
        if(token!=null){
            filterChain.doFilter(servletRequest, servletResponse);// 直接放行
        }else{
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = servletResponse.getWriter();
            JSONObject res = new JSONObject();
            res.put("msg", "错误");
            res.put("success", "false");
            out.append(res.toString());
        }
    }
​
    @Override
    public void destroy() {
//        Filter.super.destroy();
        System.out.println("destroy2-----");
    }
}

6. Controller test

The request header information was not set at the beginning, so it was not successful

@RestController
@RequestMapping("/test")
public class FilterController {
​
    @RequestMapping(value = "filter")
    public String filter1(){
        return "成功";
    }
​
}

Set request header information using postman software

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130422462