使用拦截器拦截未认证用户请求-将你拒之门外
拦截器
将用户的某个请求前中后进行插入相应操作。
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/handsometaoa/p/17022235.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了