1:java注解使用是相当频繁,特别是在搭建一些框架时,用到类的反射获取方法和属性,用的尤其多。
java中元注解有四个: @Retention @Target @Document @Inherited;
1 @Retention:注解的保留位置 2 @Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含 3 @Retention(RetentionPolicy.CLASS) //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得, 4 @Retention(RetentionPolicy.RUNTIME) //注解会在class字节码文件中存在,在运行时可以通过反射获取到 5 6 @Target:注解的作用目标 7 8 @Target(ElementType.TYPE) //接口、类、枚举、注解 9 @Target(ElementType.FIELD) //字段、枚举的常量 10 @Target(ElementType.METHOD) //方法 11 @Target(ElementType.PARAMETER) //方法参数 12 @Target(ElementType.CONSTRUCTOR) //构造函数 13 @Target(ElementType.LOCAL_VARIABLE)//局部变量 14 @Target(ElementType.ANNOTATION_TYPE)//注解 15 @Target(ElementType.PACKAGE) ///包 16 17 @Document:说明该注解将被包含在javadoc中 18 19 @Inherited:说明子类可以继承父类中的该注解
创建自定义注解类:
1 package com.liveyc.eloan.util; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 /** 9 * 要求登录标签 10 * @author Administrator 11 * 12 */ 13 @Target(ElementType.METHOD) 14 @Retention(RetentionPolicy.RUNTIME) 15 public @interface RequireLogin { 16 17 }
2:编写拦截器 java中拦截是向下传递的 所以要return false不要继续向下传递了
1 package com.liveyc.eloan.base.interceptor; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.method.HandlerMethod; 7 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 8 9 import com.liveyc.eloan.util.RequireLogin; 10 import com.liveyc.eloan.util.UserContext; 11 12 /** 13 * 登录拦截器 14 * 15 * @author Administrator 16 * 17 */ 18 public class LoginInterceptor extends HandlerInterceptorAdapter { 19 20 @Override 21 public boolean preHandle(HttpServletRequest request, 22 HttpServletResponse response, Object handler) throws Exception { 23 // 处理handler; 24 if (handler instanceof HandlerMethod) { 25 // 判断当前method上是否有标签; 26 HandlerMethod hm = (HandlerMethod) handler; 27 if (hm.getMethodAnnotation(RequireLogin.class) != null 28 && UserContext.getCurrent() == null) { 29 // r如果有,判断当前是否用户登录,如果没有登录,跳转到登录页面 30 response.sendRedirect("/login.html"); 31 return false; 32 } 33 } 34 return super.preHandle(request, response, handler); 35 } 36 37 }
3:在 spring的 xml配置文件中添加
1 <mvc:interceptors> 2 <!-- 配置登录拦截器 --> 3 <mvc:interceptor> 4 <mvc:mapping path="/**" /> 5 <bean class="com.liveyc.eloan.base.interceptor.LoginInterceptor" /> 6 </mvc:interceptor> 7 </mvc:interceptors>
4:在springmvc的 controller层 需要登入以后才能访问的方法中添加自定义注解 @RequireLogin
1 @RequireLogin 2 @RequestMapping("personal") 3 public String personal(Model model) { 4 Logininfo current = UserContext.getCurrent(); 5 model.addAttribute("userinfo",this.userinfoService.get(current.getId())); 6 model.addAttribute("account", this.accountService.get(current.getId())); 7 return "personal"; 8 }
5:启动项目 开始测试
因为没登入所以直接跳转到登录页面了
访问一个没加自定义注解的方法 页面报错
登录以后 页面正常访问