1. 程式人生 > >java的 自定義註解攔截器

java的 自定義註解攔截器

自定義的攔截器,是看了別人的文章,做的精簡,所以算是轉載

在專案中,右鍵,建立@ interface 這就是註解,在註解上加上 兩個註解 ,對這個註解進行限定

@Target(value=ElementType.METHOD)//定義了只能用於方法上
@Retention (RetentionPolicy.RUNTIME) //定義了這個攔截器存在於專案執行時
public @interface RequiredLogin {

	
}
然後建立一個攔截器,繼承HandlerInter 

Logininterceptor implements HandlerInterceptor 
對preHandle 進行重寫 ,因為它是在執行方法之前,對請求 進行攔截

@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(handler instanceof HandlerMethod){
			HandlerMethod handlerMethod=(HandlerMethod)handler;
			//用來獲取  RequiredLogin註解
			RequiredLogin requiredLogin = handlerMethod.getMethodAnnotation(RequiredLogin.class);
			if(requiredLogin !=null && UserContext.getCurrent()== null){
				response.sendRedirect("/p2p-web/login.html");
				return false;
			}
		}
		return true ;
	}

最後在springmvc 中 對攔截器 進行配置

<mvc:interceptors>
 	       <mvc:interceptor>
 	          <mvc:mapping path="/**"/>
 	          <bean  class="cn.zzsxt.p2p.util.Logininterceptor"></bean>
 	        </mvc:interceptor>
 </mvc:interceptors>
 	
如果想起作用,就需要在進行校驗的方法上,加上自己定義的註釋,進行了

@RequiredLogin
	@RequestMapping("/list")
	public String cha(Model model){
		   

我定義的是,如果方法上有 我定義的註釋,但是上下文中沒有內容  ,就會回到 登入介面。

更多功能,參考出處



 出處 : https://my.oschina.net/whhos/blog/679384