前言
SpringBoot 自定义一个过滤器
示例
1. 自定义过滤器
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import java.io.IOException;
@Slf4j
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 {
log.info("MyFilter 执行 doFilter, request addr={}, host={}", servletRequest.getRemoteAddr(), servletRequest.getRemoteHost());
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
2. 配置类
import com.idiudiu.api.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebServletConfig {
@Bean
public FilterRegistrationBean<MyFilter> myFilter() {
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("myFilter");
registrationBean.setFilter(new MyFilter()); // 注意:MyFilter 不能加 @Component, @Service... 注解
registrationBean.addUrlPatterns("/*"); // 所有路径
registrationBean.setOrder(1); // 优先级, 值越小 Filter 越靠前
return registrationBean;
}
}