SpringBoot中添加拦截器。
1.继承HandlerInterceptor接口:
public interface HandlerInterceptor { default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
实现类代码:
public class ApiHandlerInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(logger.isDebugEnabled()) { logger.debug("api用户请求拦截[" + request.getRequestURI() + "]"); } String token = request.getParameter("token"); if(!A.isLogin(token)) { if(logger.isDebugEnabled()) { logger.debug("api用户未登录"); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); Map<String, Object> resultMap = A.NoLogin(); out.append(JSONObject.toJSONString(resultMap)); } catch (Exception e) { e.printStackTrace(); } finally { if(null != out) { out.close(); } } return false; } return HandlerInterceptor.super.preHandle(request, response, handler); } }
2.实现WebMvcConfigurer接口:
@Configuration public class GlobalWebMvcConfigurer implements WebMvcConfigurer { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void addInterceptors(InterceptorRegistry registry) { /** * api 端首页和产品详情不用拦截 */ registry.addInterceptor(new ApiHandlerInterceptor()) .addPathPatterns("/api/**") .excludePathPatterns("/api/open/**"); } }
addPathPatterns是拦截指定接口,/api/**是拦截所有/api/开头的接口。
excludePathPatterns是不拦截的接口。