天天看點

java基于注解實作方法執行攔截_Spring實作自定義注解并且配置攔截器進行攔截...

有時候我們會自定義注解,并且需要配置攔截器對請求方法含有該自定義注解的方法進行攔截操作

自定義注解類

NeedToken.java

importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.Target;import staticjava.lang.annotation.RetentionPolicy.RUNTIME;@Retention(RUNTIME)

@Target({ElementType.METHOD})

@Documentedpublic @interfaceNeedToken {

}

@Target:

@Target說明了Annotation所修飾的對象範圍:Annotation可被用于 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目标。

作用:用于描述注解的使用範圍(即:被描述的注解可以用在什麼地方)

取值(ElementType)有:

1.CONSTRUCTOR:用于描述構造器

2.FIELD:用于描述域

3.LOCAL_VARIABLE:用于描述局部變量

4.METHOD:用于描述方法

5.PACKAGE:用于描述包

6.PARAMETER:用于描述參數

7.TYPE:用于描述類、接口(包括注解類型) 或enum聲明

@Retention:

@Retention定義了該Annotation被保留的時間長短:某些Annotation僅出現在源代碼中,而被編譯器丢棄;而另一些卻被編譯在class檔案中;編譯在class檔案中的Annotation可能會被虛拟機忽略,而另一些在class被裝載時将被讀取(請注意并不影響class的執行,因為Annotation與class在使用上是被分離的)。使用這個meta-Annotation可以對 Annotation的“生命周期”限制。

作用:表示需要在什麼級别儲存該注釋資訊,用于描述注解的生命周期(即:被描述的注解在什麼範圍内有效)

取值(RetentionPoicy)有:

1.SOURCE:在源檔案中有效(即源檔案保留)

2.CLASS:在class檔案中有效(即class保留)

3.RUNTIME:在運作時有效(即運作時保留)

@Documented:

@Documented用于描述其它類型的annotation應該被作為被标注的程式成員的公共API,是以可以被例如javadoc此類的工具文檔化。Documented是一個标記注解,沒有成員。

TokenInterceptor.java

importnet.sf.json.JSONObject;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.method.HandlerMethod;importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.File;importjava.lang.reflect.Method;importjava.util.HashMap;importjava.util.Map;

public class TokenInterceptor extendsHandlerInterceptorAdapter {

@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throwsException {if (handler instanceofHandlerMethod){

HandlerMethod handlerMethod=(HandlerMethod) handler;

Method method=handlerMethod.getMethod();

NeedToken needToken=method.getAnnotation(NeedToken.class);if (needToken!=null){//存在注解

}

}return true;

}

}

然後在Spring的配置檔案裡面增加或者修改

控制器方法中

@RequestMapping(value = "/showx")

@NeedToken//增加注解

public voidshow(){return null;

}