教務管理系統-Struct2註解使用攔截器(Interceptor)

在我的畢業設計——基於SSH的教務管理系統,做了一個簡單的權限控制,通過控制Action來對三個角色管理員、教師、學生進行控制。打算通過使用攔截器進行過濾。

在系統設計之初,我計劃儘量少使用配置文件,儘量使用註解,所以在使用Struct2的攔截器的時候也計劃使用註解來實現。下面是我定義的攔截器:

package com.edu.interceptor;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 攔截器:權限控制
 *
 * xukai 2016年5月18日下午4:43:11
 */
public class ActionInterceptor extends AbstractInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(ActionInterceptor.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -5004702507890081515L;

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {

		String url = ServletActionContext.getRequest().getRequestURL().toString();
		if (url.contains("login")) {
			return arg0.invoke();
		}
		String actionName = arg0.getAction().getClass().getName();
		logger.info("MethodInceptor.getAction: " + actionName);
		// 獲得身份
		String identity = (String) ActionContext.getContext().getSession().get("identity");
		// 攔截Action
		if (actionName != null && ( actionName.equals("com.edu.action.UserAction")) {
			if (identity != null && identity.equals("admin")) {
				return arg0.invoke();
			}
		}
		if (actionName != null && (actionName.equals("com.edu.action.StudentAction"))) {
			if (identity != null && identity.equals("student")) {
				return arg0.invoke();
			}
		}
		if (actionName != null && (actionName.equals("com.edu.action.TeacherAction"))) {
			if (identity != null && identity.equals("teacher")) {
				return arg0.invoke();
			}
		}
		ServletActionContext.getRequest().setAttribute("msg", "您的權限不足!");
		return "error";
	}

}
可以業務邏輯是通過獲取身份,然後決定是否能訪問某個Action。

在Action上進行註解標註:

@InterceptorRefs(value = {
		@InterceptorRef(value = "defaultStack"),
		@InterceptorRef(value = "actionInterceptor")
})
發現這裏的value竟然沒有對應的值,在使用配置文件的時候,是在配置文件中定義的,但是我沒有添加struct.xml文件,使用的是全註解,所有我百度查,是否可以在ActionInterceptor上面添加某個註解,達到標準此類事是一個攔截器,從而對應InterceptorRef中的value,這個value我猜測就是攔截器的ref-name。

最後還是沒有辦法,區服了,添加了structs.xml文件:

	<package name="xk-default" extends="json-default, struts-default">
		<interceptors>
			<!-- 配置自己定義的攔截器 -->
			<interceptor name="actionInterceptor" class="com.edu.interceptor.ActionInterceptor">
			</interceptor>
			<!-- 配置全局的攔截器棧,替換系統的攔截器棧 -->
			<interceptor-stack name="MYSTACK">
				<interceptor-ref name="actionInterceptor"></interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>

		<default-interceptor-ref name="defaultStack"></default-interceptor-ref>
		
	</package>
我隱約在structs的源碼哪裏好像看到了,攔截器的加載是通過配置文件進行讀入的,所以不能使用註解進行攔截器的標識。現在又找不到了,大神如果有辦法解決的話,求指點。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章