重要知识点:
拦截器示例
定义拦截器,实现HandlerInterceptor
在controller/interceptor路径下定义拦截器,使用@Compont注解,implements HandlerInterceptor,里面有三个方法可以重写
配置拦截器,为他指定拦截、排除的路径
WebMvcConfig implements WebMvcConfigurer,实现WebMvcConfigurer接口
首先使用@Autowired注解注入拦截器,然后重写addInterceptors()方法
拦截器应用(显示登录信息)
拦截器应用(检查登录状态)
使用拦截器的另一种方法
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {@Autowiredprivate HostHolder hostHolder;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 首先判断拦截到的是不是一个方法if(handler instanceof HandlerMethod){// 获取拦截到的Method对象HandlerMethod handlerMethod = (HandlerMethod) handler;Method method = handlerMethod.getMethod();// 获取Method的注解LoginRequired longinRequired = method.getAnnotation(LoginRequired.class);// 如果有loginRequired注解但是没有登录,说明当前方法需要登录,但是没有登录,那么拒绝后续请求,强制重定向到登录页面if(longinRequired != null && hostHolder.getUser() == null){response.sendRedirect(request.getContextPath()+"/login");return false;}}return true;}
}
自定义注解