sept1 自定義註解
@retention :Retention(保留)註解說明,這種類型的註解會被保留到哪個階段. 有三個值{1).RetentionPolicy.SOURCE —— 這種類型的Annotations只在源代碼級別保留,編譯時就會被忽略
2).RetentionPolicy.CLASS —— 這種類型的Annotations編譯時被保留,在class文件中存在,但JVM將會忽略
3).RetentionPolicy.RUNTIME —— 這種類型的Annotations將被JVM保留,所以他們能在運行時被JVM或其他
使用反射機制的代碼所讀取和使用}
@Documented :註解表明這個註解應該被 javadoc工具記錄@Target :註解使用的範圍 : method ,parameter...
demo:
import static java.lang.annotation.ElementType.METHOD;import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface isLogin {
}
注:在需要校驗用戶登入信息的接口上,controlle的方法上添加自定義的註解。
sept2 HandlerInterceptorAdapter 攔截器的實現
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class LoginInterceptor extends HandlerInterceptorAdapter {
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// handlerMethod封裝方法定義相關的信息,如類,方法,參數等
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 獲取方法上的註解
isLogin isLogin = handlerMethod.getMethodAnnotation(isLogin.class);
// 沒有islogin的註解就不判斷
if (isLogin == null) {
return true;
}
else {
// TO DO : 判斷session中是否有的用戶信息(返回true後者false)
}
return true;
}
}
xml配置:
<mvc:interceptors>
<bean class="mystudy.base.LoggedinInterceptor" />
</mvc:interceptors>
<mybatis:scan base-package="mapper" template-ref="sqlSession"/>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />