新建工具类拦截器Intercepter.class
package com.cqhpoldi.SDSY.util; import com.cqhpoldi.SDSY.validation.ErrorInfoEnum; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; /** * @Author: Poldi * @Date: 2018/6/5 下午5:20 * @Description: 拦截器 */ public class Interceptor implements HandlerInterceptor { /** * 在调用 Controller 之前 * * @param httpServletRequest 请求头 * @param httpServletResponse 返回头 * @param o * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // // 服务器报错 返回 "/error" // if (httpServletRequest.getServletPath().equals("/error")){ // throw new GlobalErrorInfoException(ErrorInfoEnum.SERVER_ERROR); // } // 验证 请求 method // String[] methods = {"POST","OPTIONS"}; // if (!Arrays.asList(methods).contains(httpServletRequest.getMethod())){ // throw new GlobalErrorInfoException(ErrorInfoEnum.METHOD_ERROR); // } // String[] whiteList = {"/admin/adminLogin","/getHotWord", "/Search", "/error"}; // if (!Arrays.asList(whiteList).contains(httpServletRequest.getServletPath())){ // // 如果请求地址不存在 whiteList 内,验证是否存在token // if (httpServletRequest.getParameter("token") == null || httpServletRequest.getParameter("token").equals("")){ // throw new GlobalErrorInfoException(ErrorInfoEnum.TOKEN_NOT_SET); // } // } return true; } /** * 在请求处理之后,Controller 调用之后 * * @param httpServletRequest 请求头 * @param httpServletResponse 返回头 * @param o * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } /** * 在整个请求结束之后执行 (主要是用于进行资源清理工作) * * @param httpServletRequest 请求头 * @param httpServletResponse 返回头 * @param o * @param e * @throws Exception */ @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
在SpringBootApplication中添加注册
@Configuration static class WebMvcConfigurer extends WebMvcConfigurerAdapter { // 增加拦截器 public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(new Interceptor()) //指定拦截器类 .addPathPatterns("/**"); //指定该类拦截的url } }