登录和未登录的权限显然是不一致的,例如登录后可以进行账号的设置,而目前即便没有登录依旧可以通过直接输入网址的方式进入设置页面,显然这是不应该的。处理的方法是对特定的某某进行标注,再根据标注进行拦截/不拦截。
使用拦截器——在方法前进行自定义注解
拦截所有请求,只处理带有该注解的方法
①自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
②在需要拦截的方法前带上该注解
③定义拦截器
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
@Autowired
private HostHolder hostHolder;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(handler instanceof HandlerMethod){
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
if(loginRequired != null && hostHolder.getUser() == null){
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
}
return true;
}
}
这里边判断条件 if(loginRequired != null && hostHolder.getUser() == null) 至关重要
添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(alphaInterceptor)
.excludePathPatterns("/css/*","/js/*","/img/*")
.addPathPatterns("/register","/login");
registry.addInterceptor(loginTicketInterceptor)
.excludePathPatterns("/css/*","/js/*","/img/*");
registry.addInterceptor(loginRequiredInterceptor)
.excludePathPatterns("/css/*","/js/*","/img/*");
}
即可