1:java注解使用是至关频繁,特别是在搭建一些框架时,用到类的反射获取方法和属性,用的尤为多。html
java中元注解有四个: @Retention @Target @Document @Inherited;java
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:说明子类能够继承父类中的该注解
建立自定义注解类:web
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不要继续向下传递了spring
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配置文件中添加mvc
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层 须要登入之后才能访问的方法中添加自定义注解 @RequireLoginapp
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:启动项目 开始测试框架
由于没登入因此直接跳转到登陆页面了ide
访问一个没加自定义注解的方法 页面报错函数
登陆之后 页面正常访问 测试