功能:判斷某些action訪問時必須用戶登陸。
攔截器代碼:
public class CheckPrivilegeInterceptor extends AbstractInterceptor {
//過濾方法
@Override
public String intercept(ActionInvocation invocation) throws Exception
{
// 判斷用戶是否登陸
User user = (User) ActionContext.getContext().getSession().get("user"); // 當前登錄用戶
String namespace = invocation.getProxy().getNamespace();
String actionName = invocation.getProxy().getActionName();
// 對應的權限URL
String privUrl = namespace + actionName;
//獲取請求的action對象
Object action=invocation.getAction();
//獲取請求的方法的名稱
String methodName=invocation.getProxy().getMethod();
//獲取action中的方法的封裝類(action中的方法沒有參數)
Method method=action.getClass().getMethod(methodName, null);
//獲取request對象
HttpServletRequest request=ServletActionContext.getRequest();
boolean isNeedLogin = CheckLoginAnnotation(request,method);
//如果登陸了
if(null==user)
{
//判斷是否有需要登錄的註解
if(isNeedLogin)
{
return "noLogin";
}
else
{
return invocation.invoke();
}
}
else
{
if (user.hasPrivilegeByUrl(privUrl))
{
// 如果有權限,就放行
return invocation.invoke();
} else {
// 如果沒有權限,就轉到提示頁面
return "noPrivilegeError";
}
}
}
/**
* 判斷是否有需要登陸註解
* @param request
* @param method
* @return
*/
public boolean CheckLoginAnnotation(HttpServletRequest request, Method method) {
if(method==null){
return false;
}
//判斷用戶請求的method上面是否存在註解
boolean isAnnotationPresent= method.isAnnotationPresent(CheckLogin.class);
return isAnnotationPresent;
}
}
自定義註解:
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckLogin {
}