在spring boot 配置servlet filter 逻辑上与配置spring 是一样的。 不过相比spring 更加简化配置的难度。 这里只需要两步
1 创建一个自定义顾虑器并继承spring filter 例如OncePerRequestFilter
public class AuthenticationFilter extends OncePerRequestFilter{private final Logger logger=LoggerFactory.getLogger(this.getClass());@Overrideprotected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)throws ServletException, IOException {//code for filtering chain.doFilter(req, resp);}}
注: 这里我使用的是OncePerRequestFilter,目的是为了保证每次request 只触发一次filter
2 在spring boot配置filter。 相当于在web.xml 配置<filter></filter> 和filter mapping url pattern
@Configuration
public class StarsFilterConfiguration {/*FilterRegistrationBean 用来配置urlpattern 来确定哪些路径触发filter */@Beanpublic FilterRegistrationBean someFilterRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter(AuthFilter());registration.addUrlPatterns("/api/rest/*");registration.setOrder(1);return registration;} /*使用annotation tag来取代<bean></bean>*/ @Bean()public Filter AuthFilter() {return new AuthenticationFilter();}
}
转载于:https://blog.51cto.com/jamesdev/1876756