1,自定义登录Interceptor类:
/**
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
/**
* 在controller 层之前拦截
* @param request
* @param response
* @param handler
* @return true 放行请求 false 拦截请求
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//request中获取token
String token = request.getHeader("token");
if (token == null) token = request.getParameter("token");
if (token == null){
//验证token有效性
Claims claims = JwtUtil.checkJWT(token);
if (claims == null){
respMsg(response , "token 不合法!");
return false;
}
// 可在此获取token的基本信息存入 session中 以方便controller层使用
request.getSession().setAttribute("userId" , claims.get("id"));
request.getSession().setAttribute("userName" , claims.get("name"));
return true;
}
//未登录
respMsg(response , "未登录");
return false;
}
/**
* 返回响应信息
* @param response
* @param msg
* @throws IOException
*/
private static void respMsg(HttpServletResponse response , String msg) throws IOException {
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(msg);
writer.close();
response.flushBuffer();
}
2,将自定义拦截器加入到Inteceptor中:
/**
* 将自定义 LoginInterceptor 加入拦截中
*/
@Configuration
public class LoginInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 放行不需登录即可访问的接口url 其他都要拦截
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("user/api/*/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
(第一步中的 JwtUtil.java 类可在本文章所在分类中找到)