@Slf4j
@Component
@Order(1)
public class TransactionFilter implements Filter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
log.info(
"Starting a transaction for req : {}",
req.getRequestURI());
chain.doFilter(request, response);
log.info(
"Committing a transaction for req : {}",
req.getRequestURI());
}
// other methods
}
@Slf4j
@Component
@Order(2)
public class RequestResponseLoggingFilter implements Filter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
log.info(
"Logging Request {} : {}", req.getMethod(),
req.getRequestURI());
chain.doFilter(request, response);
log.info(
"Logging Response :{}",
res.getContentType());
}
// other methods
}
注意在Spring Boot中我们需要使用@Component来实例化Filter从而在Spring Boot中生效。
@Bean
public FilterRegistrationBean<UrlFilter> loggingFilter(){
FilterRegistrationBean<UrlFilter> registrationBean
= new FilterRegistrationBean<>();
registrationBean.setFilter(new UrlFilter());
registrationBean.addUrlPatterns("/users/*");
return registrationBean;
}