1.拦截器定义
这里定义一个jwt拦截器,继承HandlerInterceptor 重写里面的方法实现拦截
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
/**
* 操作之前拦截
* @param request
* @param response
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
log.info("经过拦截器");
String token = request.getHeader("Authorization");
if (StringUtils.isEmpty(token)){
throw new Exception("权限不足");
}
if (StringUtils.isNotEmpty(token)){
//对令牌进行验证
try {
//解析令牌
Claims claims = JJwtUtiles.parseToken(token);
}catch (Exception e){
throw new Exception("令牌有误");
}
}
return true;
}
/**
* 操作之后拦截
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
/**
* 最终释放资源
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
2.注册拦截器
@Configuration表明为一个配置类,继承WebMvcConfigurationSupport 注册拦截器
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
private JwtInterceptor jwtInterceptor;
/**
* 注册拦截器
* @param registry
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//声明拦截对象 和请求 (拦截所有请求 除登录外)
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/**/login/**");
}
}