@Component
public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
System.out.println("TestInterceptor-----------------preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("TestInterceptor-----------------postHandle");
}
}
@Component
public class JavasmWebMvcConfiguration implements WebMvcConfigurer {
@Resource
TestInterceptor testInterceptor;
@Resource
LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//当前的这个方法,是管理拦截器的
//registry注册拦截器
registry.addInterceptor(testInterceptor)
.addPathPatterns("/game/**")
.excludePathPatterns("/game/list");
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login/**");
}
}
-
练习
希望拦截器,拦截请求,校验登录的用户
一部分接口,必须登录之后才能访问,也有一部分接口,不登录也可以访问
通过自定义注解,来灵活区分哪个接口需要拦截
-
自定义注解
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface JavasmAuth { }
@Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //如果 被访问的方法,有自定义注解,就走下面的流程,没有,直接放过 HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); //获取 method对象上面的JavasmAuth注解 JavasmAuth annotation = method.getAnnotation(JavasmAuth.class); if (annotation == null){ //说明 方法上面 没有加密注解,不需要加密 return true; } //代码执行到这里,说明 annotation不是null,方法上面与加密注解 HttpSession session = request.getSession(); Object user = session.getAttribute("user"); if (user!=null){ return true; } throw new JavasmException(ExceptionEnum.NotLoginError); } }
使用
@JavasmAuth @GetMapping("/list") public R queryList() { return R.ok(gameService.queryAll()); }