第04篇:自定义filter
方案
FilterRegistrationBean bean@WebFilter注解 + @ServletComponentScan
流程
定义filter class配置filter bean
1. filter class
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig
) throws ServletException
{
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest
, ServletResponse servletResponse
, FilterChain filterChain
)
throws IOException
, ServletException
{
HttpServletRequest request
= (HttpServletRequest
)servletRequest
;
System
.out
.println("filter, url: " + request
.getRequestURI());
filterChain
.doFilter(servletRequest
, servletResponse
);
}
}
2. filter bean
@Bean
public FilterRegistrationBean
filterRegistrationBean() {
FilterRegistrationBean registrationBean
= new FilterRegistrationBean();
registrationBean
.setFilter(new MyFilter());
registrationBean
.addUrlPatterns("/*");
registrationBean
.addInitParameter("param", "value");
registrationBean
.setName("MyFilter");
//设置过滤器顺序
registrationBean
.setOrder(1);
return registrationBean
;
}
注解方案
启动类注解:@ServletComponentScan Filter实现类注解:
@WebFilter(filterName
= "Second Filter", urlPatterns
= "/*",
initParams
= {
@WebInitParam(name
= "author", value
= "XX")
})
public class MyFilter implements Filter {
}