【springboot】拦截器 校验
1.创建一个拦截器类文件
preHandle返回true则放行,若放回false则拒绝请求 后面的资源不会再显示给前端
/***
* 拦截器
*/
public class MyinInterceptor implements HandlerInterceptor {
@Autowired
private JwtToken jwtToken;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// OPTIONS请求直接放行
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
return true;
}
//从请求头中获取token
String token = request.getHeader("Authorization");
// 设置输出对象 和 编码
PrintWriter out = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// 如果没有token
if (ObjectUtil.isNull(token)){
try {
JSONObject res = new JSONObject();
res.put("code","401");
res.put("data", "用户未登录!");
res.put("msg", "失败");
out = response.getWriter();
out.append(res.toString());
return false;
} catch (Exception e) {
e.printStackTrace();
response.sendError(500);
return false;
}
}
// 如果带有token,进行验证
try {
boolean b = jwtToken.verifyToken(token);
}catch (Exception e){
JSONObject res = new JSONObject();
res.put("code","402");
res.put("data", "无权限!");
res.put("msg", "失败");
out = response.getWriter();
out.append(res.toString());
return false;
}
// return HandlerInterceptor.super.preHandle(request, response, handler);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
2.创建mvc配置类文件
设置哪些接口需要拦截和放行,此文件是必须的,否则上面的拦截器不会生效
@Configuration
public class MVCconfiguration implements WebMvcConfigurer {
@Bean
MyinInterceptor getinInterceptor(){
return new MyinInterceptor();
}
//校验拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getinInterceptor())
.addPathPatterns("/**")// 添加所有路径需要校验
.excludePathPatterns("/user/login","/user/verify","/user/register","/user/regCode","/alipaynotify");//不需要拦截的接口
}
}