SpringBoot自定义 Filter并配置

过滤器不用说了,项目中众多常用的地方,比如客户登入认证等。下边来探视哪些创制二个Filter并交付Spring容器管理

1.新建MyFilter,要做的校验,能够在doFilter重载函数中实行
import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import java.io.IOException;public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("this is MyFilter,url :"+request.getRequestURI; filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { }}
2.将自定义 Filter 参预过滤链
import com.sqlb.qiqi.filter.MyFilter;import org.apache.catalina.filters.RemoteIpFilter;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class FilterConfiguration { @Bean public RemoteIpFilter remoteIpFilter() { return new RemoteIpFilter(); } @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter; registration.addUrlPatterns; registration.addInitParameter("paramName", "paramValue"); registration.setName("MyFilter"); registration.setOrder; return registration; }}

增多完后运维项目,就足以生效了。访问任性的
Url,都会看见调整台打印如下音讯:

this is MyFilter,url :/xxx

相关文章