1.定义一个自己的过滤器,实现Filter接口,使用@WebFilter(filterName = "myFilter", urlPatterns = "/*")注解来注册命名过滤器,指定过滤地址。
package com.huike.base.servlet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@WebFilter(filterName = "myFilter")
public class PagesSecurityFilter implements Filter {
@Qualifier("tokenUserInfoService")
@Autowired(required = true)
private TokenUserInfoService tokenUserInfoService;
@Qualifier("publickeyService")
@Autowired(required = true)
private PublickeyService publickeyService;
private static Log log = LogFactory.getLog(PagesSecurityFilter.class);
private static final String X_REQUESTED_WITH = "X-Requested-With";
public PagesSecurityFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 设置字符集
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
spring boot还提供了FilterRegistrationBean来进行filter的配置
package com.huike.base.servlet;
import javax.servlet.Filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StarsFilterConfiguration {
/* FilterRegistrationBean 用来配置urlpattern 来确定哪些路径触发filter */
private static Log log = LogFactory.getLog(StarsFilterConfiguration.class);
@Bean
public FilterRegistrationBean someFilterRegistration() {
log.info("StarsFilterConfiguration..........");
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(AuthFilter());
registration.setEnabled(true); // 设置是否可用
registration.addUrlPatterns("/api/app/rest/*","/api/web/rest/*"); // 需要进行过滤的url
// registration.addUrlPatterns("/api/app/rest/*");
registration.setOrder(1); // 设置过滤器的顺序,可选
return registration;
}
/* 使用annotation tag来取代<bean></bean> */
@Bean()
public Filter AuthFilter() {
return new PagesSecurityFilter();
}
}
3.有一个地方要注意,如果@WebFilter(filterName = "myFilter", urlPatterns = "/*")中配置的过滤地址优先级大于在FilterRegistrationBean中配置的过滤地址。