Springboot使用过滤器配置类统一管理过滤器
你猜
阅读:732
2021-04-01 11:08:12
评论:0
1、配置过滤器管理类
注;三个过滤器order顺序小的先执行
@Configuration
public class FilterConfig {
/** 日志记录 */
@Bean
public FilterRegistrationBean<AppHttpLogFilter> httpLogFilterRegistration() {
FilterRegistrationBean<AppHttpLogFilter> registration = new FilterRegistrationBean<>();
registration.addUrlPatterns( "/*" );
registration.setFilter( new AppHttpLogFilter() );
registration.setName( "httpLogFilter" );
registration.setOrder( Integer.MAX_VALUE-2 );
return registration;
}
/** 跨域处理 */
@Bean
public FilterRegistrationBean<AppCorsFilter> corsFilterRegistration() {
FilterRegistrationBean<AppCorsFilter> registration = new FilterRegistrationBean<>();
registration.addUrlPatterns( "/*" );
registration.setFilter( new AppCorsFilter() );
registration.setName( "corsFilter" );
registration.setOrder( Integer.MAX_VALUE-1 );
return registration;
}
/** XSS过滤 */
@Bean
public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
registration.addUrlPatterns( "/*" );
registration.setDispatcherTypes(DispatcherType.REQUEST );
registration.setFilter( new XssFilter() );
registration.setName( "xssFilter" );
registration.setOrder( Integer.MAX_VALUE );
return registration;
}
}
2.过滤器实现解决跨域问题
public class AppCorsFilter implements Filter
{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException
{
HttpServletRequest request;
HttpServletResponse response;
String sOrigin;
request = (HttpServletRequest)servletRequest;
response = (HttpServletResponse)servletResponse;
//==== 处理跨域问题
//若有Origin,说明前端请求时启用了跨域设置(为启用Session)
sOrigin = request.getHeader("Origin");
if( StringUtils.isEmpty(sOrigin) )
sOrigin = "*"; //"http://" + request.getRemoteHost() + ":" + request.getRemotePort();
response.setHeader("Access-Control-Allow-Origin", sOrigin);
response.setHeader("Access-Control-Allow-Credentials", "true");
//下面几个好像在响应OPTIOINS请求时才是必需
if( RequestMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod()) )
{
response.setHeader("Access-Control-Allow-Headers", "Content-Type,x-requested-with,Authorization,token");
response.setHeader("Access-Control-Allow-Methods", "HEAD,GET,POST,PUT,DELETE,OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
}
//必须放到设置Header之后,否则导致返回403错误
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。