源码地址:仓库 - Allen (datadogapache) - Gitee.com
一.登录校验成功放行
/**
* 进⼊到controller之前的⽅法
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
try {
String accesToken = request.getHeader("token");
if (accesToken == null) {
accesToken = request.getParameter("token");
}
if (StringUtils.isNotBlank(accesToken)) {
Claims claims = JWTUtils.checkJWT(accesToken);
if (claims == null) {
//告诉登录过期,重新登录
sendJsonMessage(response, JsonData.buildError("登录过期,重新登录"));
return false;
}
Integer id = (Integer) claims.get("id");
String name = (String) claims.get("name");
request.setAttribute("user_id", id);
request.setAttribute("name", name);
return true;
}
}catch (Exception e){}
sendJsonMessage(response, JsonData.buildError("登录过期,重新登录"));
return false;
}
二.登录不成功返回json数据
/**
* 响应json数据给前端
* @param response
第2集 ⼩滴课堂实战之loginInterceptor注册和放⾏路径
简介:loginInterceptor 拦截器注册和路径校验配置
继承 WebMvcConfigurer
配置拦截路径和放⾏路径
* @param obj
*/
public static void sendJsonMessage(HttpServletResponse response,
Object obj){
try{
ObjectMapper objectMapper = new ObjectMapper();
response.setContentType("application/json; charset=utf-
8");
PrintWriter writer = response.getWriter();
writer.print(objectMapper.writeValueAsString(obj));
writer.close();
response.flushBuffer();
}catch (Exception e){
e.printStackTrace();
}
}
注解:返回给前端的数据需要序列化,运用objectMapper序列化参数。
三.拦截器注册和路径校验配置
/**
* 拦截器配置
*
* 不⽤权限可以访问url /api/v1/pub/
* 要登录可以访问url /api/v1/pri/
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截全部
registry.addInterceptor(loginInterceptor()).addPathPatterns("/api/v1/pri/*/*/*
*")
//不拦截哪些路径 斜杠⼀定要加
.excludePathPatterns("/api/v1/pri/user/login","/api/v1/pri/user/register");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
注解:实现WebMvcConfigure接口重写addInterceptors方法,添加拦截路径时需注意路径的写法,excludePathPatterns("/api/v1/pri/user/login","/api/v1/pri/user/register")指定不需要拦截的路径。 最后要调用父类的addInterceptors方法提交注册器。