//自定义拦截器
//第一步:创建一个拦截器类实现拦截器接口
/*里面有三个可以实现的方法,
destroy():销毁时执行
init():初始化时执行
intercept(ActionInvocation invocation)
在里面定义自己需要的方法
*/
package cn.itcast.interceptor;
import java.awt.event.InvocationEvent;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class PermissionInterceptor implements Interceptor {
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
Object user = ActionContext.getContext().getSession().get("user");
if(user!=null) return invocation.invoke();
ActionContext.getContext().put("message", "你没有执行的权限");
return "success";
}
}
//第二步:在配置文件中操作
/*
1)、在配置文件中注册拦截器
<interceptors>
<interceptor name="permission" class="cn.itcast.interceptor.PermissionInterceptor"/>
</interceptors>
2)、如果在配置文件中只注册自定义拦截器,那么struts2中默认拦截器就会失去效应。所以需要定义拦截器栈
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="permission"/>
</interceptor-stack>
注意:一般把默认的放在自定义的前面
3)、我们可以设置包内默认使用的拦截器:在包内所有action都能使用这个“默认”拦截器
<default-interceptor-ref name="permissionStack"></default-interceptor-ref>
注意:这个“默认”拦截器需要放在全局视图之前否则会报错
*/
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>
<package name="itcast" namespace="/control/employee" extends="struts-default">
<interceptors>
<interceptor name="permission" class="cn.itcast.interceptor.PermissionInterceptor"/>
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="permission"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="permissionStack"></default-interceptor-ref>
<global-results>
<result name="success">/WEB-INF/page/message.jsp</result>
</global-results>
<action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
</action>
</package>
</struts>