spring mvc 处理 所有request
1.spring mvc filter 所有request
@WebFilter(urlPatterns = {"/*" }) public class AuthenticationFilter implements Filter{ private static Logger logger = Logger.getLogger(AuthenticationFilter.class); @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.info("checking client id in filter"); HttpServletRequest request = (HttpServletRequest) arg0; String clientId = request.getHeader("clientId"); if (StringUtils.isNotEmpty(clientId)) { chain.doFilter(request, response); } else { logger.error("client id missing."); } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
2.用 Interceptor
(1)Implement HandlerInterceptor interface and add a @Component annotation to your class
@Component public class SecurityInterceptor implements HandlerInterceptor { private static Logger log = LoggerFactory.getLogger(SecurityInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.getSession(true); if(isLoggedIn(request)) return true; response.getWriter().write("{\"loggedIn\":false}"); return false; } private boolean isLoggedIn(HttpServletRequest request) { try { UserSession userSession = (UserSession) request.getSession(true).getAttribute("userSession"); return userSession != null && userSession.isLoggedIn(); } catch(IllegalStateException ex) { return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
(2) Configure your Interceptor
@Configuration public class WebConfig implements WebMvcConfigurer { private HandlerInterceptor securityInterceptor; @Autowired public void setSecurityInterceptor(HandlerInterceptor securityInterceptor) { this.securityInterceptor = securityInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(securityInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/logout"); } }