Struts2規定使用者自定義攔截器必須實作com.opensymphony.xwork2.interceptor.Interceptor接口
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class PermissionInterceptor implements Interceptor {
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Object user=ActionContext.getContext().getSession().get("user");
if(user!=null)
return invocation.invoke();//過濾成功則繼續執行action中result
ActionContext.getContext().put("message", "你沒有權限執行該操作!");
return "success";//不成功則執行另一個視圖
}
}
配置Struts2攔截器
Struts2攔截器需要在struts.xml中聲明,如下struts.xml配置檔案
<package name="employee" namespace="/control/employee" extends="struts-default">
<interceptors>
<interceptor name="permission" class="cn.ljf.PermissionInterceptor"></interceptor>
<interceptor-stack name="permissionStack"> <!-- 攔截器棧 -->
<interceptor-ref name="defaultStack"></interceptor-ref> <!-- 使用了自定義的攔截器,預設的将失效 -->
<interceptor-ref name="permission"></interceptor-ref>
</interceptor-stack>
</interceptors>
<global-results>
<result name="success">/message.jsp</result>
</global-results>
<action name="list_*" class="cn.ljf.HelloWorldAction" method="{1}">
<interceptor-ref name="permissionStack"></interceptor-ref><!-- 添加攔截器 -->
</action>
</package>
