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:啟動項目 開始測試
因為沒登入所以直接跳轉到登錄頁面了
訪問一個沒加自定義注解的方法 頁面報錯
登錄以后 頁面正常訪問