springMvc之拦截器的使用

2022年10月23日08:14:32

自定义拦截器,实现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("/**");// 拦截除了"/user/**的所有请求路径}}
  • 作者:小白划水
  • 原文链接:https://blog.csdn.net/qq_42218187/article/details/123617836
    更新时间:2022年10月23日08:14:32 ,共 1125 字。