首先定义一个类:
ControllerInterceptor
内容如下:
public class ControllerInterceptor implements HandlerInterceptor { private static final Logger log = LoggerFactory.getLogger(ControllerInterceptor.class); @Override //这个方法是在进行控制器之前执行,可以在这里进行验证,我这里是进行对数据的请求进行jwt的验证,验证通过之后才可以进入控制器 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { Cookie[] cookies= httpServletRequest.getCookies(); if (cookies!=null){ for (Cookie cookie:cookies){ if (cookie.getName().equals("token")){ //说明拿到值了,进行token解密 JsonData jsonData= jwtutils.checkjwts(cookie.getValue()); if (jsonData.getCode()==200){ //解密成功 return true; } } } } return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("--------------处理请求完成后视图渲染之前的处理操作---------------"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("---------------视图渲染之后的操作-------------------------0"); } }
定义好这个拦截器之后我们需要让springboot知道我们有这个拦截器,所以我们需要定义一个类:
WebAppConfig
内容如下:
/** * function:让拦截器添加到springboot中 */ @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(new ControllerInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/login1"); } }