Spring Boot 自定义Filter
一、Filter功能
它使用户可以改变一个 request和修改一个response. Filter 不是一个servlet,它不能产生一个response,它能够在一个request到达servlet之前预处理request,也可以在离开 servlet时处理response.换种说法,filter其实是一个 “servlet chaining” (servlet 链).
一个Filter包括:
1)、在servlet被调用之前截获;
2)、在servlet被调用之前检查servlet request;
3)、根据需要修改request头和request数据;
4)、根据需要修改response头和response数据;
5)、在servlet被调用之后截获.
二、自定义Filter
- 方法一:
-
实现filter方法
public class GlobalFilter 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; String requestURI = request.getRequestURI(); System.out.println(requestURI); filterChain.doFilter(request, servletResponse); } @Override public void destroy() { } }
-
加载Filter 配置
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean filterRegistration(){ // 新建过滤器注册类 FilterRegistrationBean registration = new FilterRegistrationBean(); // 添加自定义 过滤器 registration.setFilter(globalFilter()); // 设置过滤器的URL模式 registration.addUrlPatterns("/*"); //设置过滤器顺序 registration.setOrder(1); return registration; } @Bean public GlobalFilter globalFilter(){ return new GlobalFilter(); } }
-
方法二(推荐)
-
自定义MyFilter, 如果请求URI 包含
my
, 则进行下一步处理@WebFilter(filterName = "myFilter", urlPatterns = "/*") public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init..."); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String requestURI = request.getRequestURI(); if(requestURI.contains("my")){ System.out.println("成功啦。。。, 请求URI是:" + requestURI); } filterChain.doFilter(request, servletResponse); } @Override public void destroy() { System.out.println("destroy..."); } }
-
在Application 启动类 添加
@ServletComponentScan
注解@ServletComponentScan @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-