1.检查登录状态
我们上次写的拦截器,是拦截所有请求,给请求全部带上当前用户信息。并且能够达到,有用户和无用户登录界面不同的效果。
这次的拦截器,是为了有人在知道url的情况下,在未登录的状态下也能访问如用户设置的方法。所以需要对部分需要登录才能访问的controller进行拦截。
此次我们想拦截哪些路径不去配置文件指定。而是通过注解的方式,在controller方法上加个注解,就表示我们要拦截这个方法。
1.自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
2.写个拦截器,拦截所有带有注解的方法,并且判断是否登陆。没登录重定向到login页面,并拦截请求
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
@Autowired
private HostHolder hostHolder;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断当前拦截的是不是controller方法。HandlerMethod就代表controller方法
if (handler instanceof HandlerMethod){
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
LoginRequired annotation = method.getAnnotation(LoginRequired.class);
//此方法需要登录,但是没有登录
if (annotation != null && hostHolder.getUser() == null){
response.sendRedirect(request.getContextPath()+"/login");
return false;
}
}
return true;
}
}
3.注册拦截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private CommunityInterceptor communityInterceptor;
@Autowired
private LoginRequiredInterceptor loginRequiredInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(communityInterceptor)
.excludePathPatterns("/**/*.css","/**/*.js","/**/*.png","/**/*.jpg","/**/*.jpeg");
registry.addInterceptor(loginRequiredInterceptor).excludePathPatterns("/**/*.css","/**/*.js","/**/*.png","/**/*.jpg","/**/*.jpeg");
}
}
4.使用注解
@LoginRequired
@RequestMapping(path = "/setting",method = RequestMethod.GET)
public String getSettingPage(){
return "/site/setting";
}