标签:拦截器 return springboot 登录 预处理 token LoginRequired new public
1.创建LoginRequired和ReturnPage注解,分别表示 是否需要登录来访问 和 返回数据还是页面(因为我没怎么学前端只会new Vue(..) 所以只引入了个vue.js和axios.js 没法通过this.$router.push切换页面)。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnPage {
}
2.实现WebMvcConfigurer 加上Configuration注解 添加放行和拦截
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] addPath = {"/**"};
String[] excludePath = {"/login", "/", "/swagger-ui"};
registry.addInterceptor(new MyInterceptor()).addPathPatterns(addPath).excludePathPatterns(excludePath);
}
}
3.没啥好说的
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) { //这样写静态资源好像都放行了就不用在上面exclude path里加了
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
if (loginRequired == null) { //没有加LoginRequired注解 就不用管了
return true;
}
Cookie[] cookies = request.getCookies(); //我是把token存在cookies里 根据实际修改
for (Cookie cookie: cookies) {
if (cookie.getName().equals("token")) {
String token = cookie.getValue();
System.out.println("Token: " + token);
if (StringUtils.isBlank(JwtUtils.getUserIdByJwtToken(token))) {
System.out.println("登录过期");
throw new GlobalException(20002, "登录信息过期,请重新登录");
} else {
return true;
}
}
}
ReturnPage returnPage = method.getAnnotation(ReturnPage.class);
if (returnPage == null) { //返回形式是数据 抛异常让GlobalExceptionHandler处理返回json消息
System.out.println("登录过期");
throw new GlobalException(20002, "操作异常,请重新登录");
} else { //访问/login路径 返回到page/login.html
response.sendRedirect("/login");
return false;
}
}
}
标签:拦截器,return,springboot,登录,预处理,token,LoginRequired,new,public 来源: https://blog.csdn.net/m0_52640724/article/details/122735694
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。