HandlerInterceptor
场景:
1、日志记录
2、权限校验
3、性能监控
下面是在用户进入购物车后,登录和未登录校验
public class LoginInterceptor extends HandlerInterceptorAdapter {
private JwtProperties jwtProperties;
//定义一个线程池,存放登录用户
private static final ThreadLocal<UserInfo> t=new ThreadLocal<>();
public LoginInterceptor(JwtProperties jwtProperties){
this.jwtProperties=jwtProperties;
}
/**
*预处理回调方法(如登录校验)
*返回值为true 继续执行;false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//查询token 401身份验证
String token = CookieUtils.getCookieValue(request,jwtProperties.getCookieName());
if (StringUtils.isBlank(token)){
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
try {
// 解析成功,证明已经登录
UserInfo user = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
// 放入线程域
t.set(user);
return true;
} catch (Exception e){
// 抛出异常,证明未登录,返回401
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
}
/**
* 整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
t.remove();
}
public static UserInfo getLoginUser(){
return t.get();
}
}
HandlerInterceptorAdapter
除此之外还有两个方法
/**
* This implementation is empty.
* 是在preHandle执行完,进行controller调接口返回结果后执行 主要是对modelAndView进行操作
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
/**
* This implementation is empty.
*
*/
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
}
WebMvcConfigurer在SpringMVC注解配置启用过滤器
@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class MvcConfig implements WebMvcConfigurer {
//jwt加密
@Autowired
private JwtProperties jwtProperties;
@Bean
public LoginInterceptor loginInterceptor(){
return new LoginInterceptor(jwtProperties);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//路径全屏蔽
registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
//允许的路径
//registry.addInterceptor(loginInterceptor()).excludePathPatterns("/");
}
}