自定义拦截器,实现HandlerInterceptor接口
publicclassJWTInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
String token= request.getHeader("token");
Map<String,Object> map=newHashMap<>();try{
JWTUtils.verify(token);returntrue;}catch(TokenExpiredException e){
map.put("state",false);
map.put("msg","Token已经过期!!!");}catch(SignatureVerificationException e){
map.put("state",false);
map.put("msg","签名错误!!!");}catch(AlgorithmMismatchException e){
map.put("state",false);
map.put("msg","加密算法不匹配!!!");}catch(Exception e){
e.printStackTrace();
map.put("state",false);
map.put("msg","无效token~~");}
String json=newObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);returnfalse;}}
注册拦截器,实现WebMvcConfigurer ,将自定义的拦截器注册进来
@ConfigurationpublicclassInterceptorConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){
registry.addInterceptor(newJwtTokenInterceptor()).excludePathPatterns("/user/**").addPathPatterns("/**");}}