方式1
1.添加component注解
2.实现javax.servlet.Filter
3.重写init,doFilter,destory方法
方式2
添加
1添加@webfilter注解、@Order(1)注解,可以设定过滤的路径
@WebFilter(filterName = "**",urlPatterns = {"*.html"})
2.实现javax.servlet.Filter
3在启动类application上加注解@ServletComponentScan
@ServletComponentScan(basePackages = "com.zz.project")
另外:如果我们的应用程序运行在一台负载均衡代理服务器后方,因此需要将代理服务器发来的请求包含的IP地址转换成真正的用户IP。Tomcat 8 提供了对应的过滤器:RemoteIpFilter。通过将RemoteFilter这个过滤器加入过滤器调用链即可使用它
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
System.out.println("this is my RemoteIpFilter");
return new RemoteIpFilter();
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
System.out.println("this is my FilterRegistrationBean");
filterRegistrationBean.setFilter(new MyFilter());
List<String> urlPatterns = new ArrayList<>();
urlPatterns.add("/*");
filterRegistrationBean.setUrlPatterns(urlPatterns);
filterRegistrationBean.addInitParameter("paramName","paramValue");
filterRegistrationBean.setName("MyFilter");
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}
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 httpServletRequest = (HttpServletRequest)servletRequest;
System.out.println("this is MyFilter,url :" + httpServletRequest.getRequestURL());
filterChain.doFilter(httpServletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
}