使用拦截器拦截未认证用户请求-将你拒之门外

拦截器

将用户的某个请求前中后进行插入相应操作。

preHandle

调用时间:Controller方法处理之前
执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序一个接一个执行
若返回false,则中断执行,注意:不会进入afterCompletion

postHandle

调用前提:preHandle返回true
调用时间:Controller方法处理完之后,DispatcherServlet进行视图的渲染之前,也就是说在这个方法中你可以对ModelAndView进行操作
执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序倒着执行
备注:postHandle虽然post打头,但post、get方法都能处理

afterCompletion

调用前提:preHandle返回true
调用时间:DispatcherServlet进行视图的渲染之后
多用于清理资源

使用拦截器拦截未认证用户

public abstract class AuthorizationInterceptor implements HandlerInterceptor{  
    public String token;
    private static final ThreadLocal<Map<String, Object>> userInfoLocal = new ThreadLocal<>();
    // 在业务处理器处理请求之前被调用  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{  
      token=request.get("");//从请求中获取token  
      // 处理token,如果验证通过,存进userInfoLocal供以后使用,不通过则直接拒之门外。
      return true;  
    }  
    // 在业务处理器处理请求完成之后,生成视图之前执行  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  
      throws Exception{  
    }  
    // 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  
      throws Exception{  
      userInfoLocal.remove();//将用户信息删除,防止出现内存泄漏
    }  
}

【最后】RequestInterceptor实现WebMvcConfigurer

@Configuration
public class RequestInterceptor implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // auth interceptor
        registry.addInterceptor(new AuthorizationInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(AuthorizationInterceptorConfig.getExcludePathPatterns())
                // swagger 相关
                .excludePathPatterns("/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs");
    }
}

参考网页:https://www.cnblogs.com/xzjf/p/11847075.html

posted @   帅气的涛啊  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示

目录