Spring Boot自定义Filter

Filter功能

Filter使用户可以改变一个Request和修改一个Response。Filter不是一个Servlet,它不能产生一个Response,它能够在一个Request到达Servlet之前预处理Request,也可以在离开 Servlet时处理Response。换种说法,Filter其实是一个 “Servlet Chaining” (Servlet链)。

一个Filter包括:

  • 在servlet被调用之前截获
  • 在servlet被调用之前检查servlet request
  • 根据需要修改request头和request数据
  • 根据需要修改response头和response数据
  • 在servlet被调用之后截获

自定义Filter

第一种方法(稍麻烦)

1、实现Filter 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Slf4j
public class MyFilter implements Filter {
@Override
public void destroy() {

}

@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) sRequest;
HttpServletResponse response = (HttpServletResponse) sResponse;
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
log.info("requestURI: " + requestURI + ", requestURL: " + requestURL);
filterChain.doFilter(request, response);
}

@Override
public void init(FilterConfig config) {

}
}

2、加载Filter配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@Slf4j
public class WebConfiguration {
@Bean
public FilterRegistrationBean testFilterRegistration() {
// 新建过滤器注册类
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
// 添加自定义过滤器
registration.setFilter(new MyFilter());
// 设置过滤器的URL模式
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
// 设置拦截器的名称
registration.setName("MyFilter");
// 设置过滤器顺序
registration.setOrder(1);
return registration;
}
}

第二种方法(简洁,推荐使用这种)

1、添加 @WebFilter 自定义MyFilter,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
@Slf4j
public class MyFilter implements Filter {
@Override
public void destroy() {

}

@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) sRequest;
HttpServletResponse response = (HttpServletResponse) sResponse;
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
log.info("requestURI: " + requestURI + ", requestURL: " + requestURL);
filterChain.doFilter(request, sResponse);
}

@Override
public void init(FilterConfig config) {

}
}

2、在Application 启动类 添加 @ServletComponentScan 注解

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :