- 使用拦截器
- 在方法前标注自定义注解
- 拦截所有请求,只处理带有该注解的方法
- 自定义注解
- 常用的元注解:
- @Target、@Retention、@Document、@Inherited
- 如何读取注解:
- Method.getDeclaredAnnotations ()
- Method.getAnnotation (Class annotationClass)
限制用户在未登录前访问到登录后的页面或者普通用户访问到管理员页面。
定义注解
利用注解,统一处理。新建一个annotation包,包下新建一个annotation类。
自定义注解需要用到常见的几个元注解,@Target是作用目标,可以是方法、类等。@Retention是生效时间,运行时有效、编译时有效等。这两个基本时必须写的,@Document文档是否记录,@Inherited是否继承。
package com.neu.langsam.community.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
定义好注解后,在需要登录才能访问的方法上面加上注解,目前主要就是设置界面和上传头像需要登录。
定义拦截器
使用注解标记需要处理的方法后,定义拦截器进行统一处理。这里只对响应前进行处理,也就是只重写preHandle。
首先判断拦截对象是不是一个方法,如果是的话讲Object对象转型成HandlerMethod对象。获取拦截的方法,查找该方法有没有我们写的@LoginRequired注解。有的话看hostHolder里有没有user,如果有注解没user就重定向到登录页面,这里不是在controller层,所以需要用respons重定向。
package com.neu.langsam.community.controller.interceptor;
import com.neu.langsam.community.annotation.LoginRequired;
import com.neu.langsam.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@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;
}
}
运行项目,在地址栏尝试直接访问设置页面,localhost:8080/community/user/setting,会发现跳转到了登录页面。