【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等,有几种注册方法
- 使用
@WebFilter
、@WebServlet
、@WebListener
注解来标识类 - 使用
FilterRegistrationBean
、ServletRegistrationBean
来对Filter
、Servlet
进行自定义注册 - 使用
@Bean
来自动添加,添加后默认的过滤路径为/*