本文主要是介绍HandlerInterceptor 拦截器,生成dongtai token,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
// 实现拦截器
@Component
public class loginCheckInterceptor implements HandlerInterceptor {@Override //目标方法运行前执行,public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String url = request.getRequestURL().toString();if(url.contains("/login")){System.out.println("next step");return true;}String token = request.getHeader("token");System.out.println("目标方法运行前执行--->>token,"+token);if(token == null || token.length() < 0){return false;}try {Claims claims = JwtUtils.checkToken(token);System.out.println("目标方法运行前执行,");return true;} catch (Exception e){AjaxResult jssd = AjaxResult.error("token Error");JSONObject jsonObject = new JSONObject(jssd);response.getWriter().write(String.valueOf(jsonObject));return false;}}@Override //目标方法运行后public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("目标方法运行前执hou,");}@Override // 视图完毕后,最后运行public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("目标方法运行前执最后允许,");}
}
webMVCconfig
@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate loginCheckInterceptor loginCheckInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {List<String> patterns = new ArrayList<>();patterns.add("/login");// 排除不过滤的数据registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns(patterns);}
}
token合法性
/*** 验证 Token 合法性* @param jwt*/public static Claims checkToken(String jwt) {Claims claims = Jwts.parser().setSigningKey(singKey).parseClaimsJws(jwt).getBody();return claims;}
这篇关于HandlerInterceptor 拦截器,生成dongtai token的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!