【spring boot】FilterRegistrationBean介绍

原文地址:https://www.cnblogs.com/lodor/p/7568765.html

前言

      以往的javaee配置过滤器是在web.xml中配置的,如下代码

   

复制代码
<filter>
     <filter-name>TestFilter</filter-name>
        <filter-class>com.cppba.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>TestFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <init-param>
       <param-name>paramName</param-name>
       <param-value>paramValue</param-value>
    </init-param>
</filter-mapping>
复制代码

     而spring boot 是没有这个配置的,怎么办?

解决办法

    定义一个自定义的过滤器,类似原来的模式

   

复制代码
package com.cppba.filter;

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

public class TestFilter 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("TestFilter");
    }

    @Override
    public void destroy() {

    }
}
复制代码

 

    主程序启动文件,增加

复制代码
@Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TestFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("testFilter");
        registration.setOrder(1);
        return registration;
    }
复制代码

 

总结:

   

Spring Boot针对Servlet、Filter等,有几种注册方法
  1. 使用@WebFilter@WebServlet@WebListener注解来标识类
  2. 使用FilterRegistrationBeanServletRegistrationBean来对FilterServlet进行自定义注册
  3. 使用@Bean来自动添加,添加后默认的过滤路径为 /*
posted @ 2021-08-11 13:29  eyesfree  阅读(487)  评论(0编辑  收藏  举报