自定义拦截器需要实现Interceptor接口,重写里面的方法
和一般的动态代理一样,通过invoke方法执行
package com.leeket.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MySelfInterceptor implements Interceptor {
public void destroy() {
}
public void init() {
// TODO Auto-generated method stub
}
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";
}
}
自定义拦截器在struts.xml中的配置如下
<interceptors>
<interceptor name="myinterceptor" class="com.leeket.interceptor.MySelfInterceptor"></interceptor><!--配置子定义拦截器-->
<interceptor-stack name="myinterceptorStack"><!--配置自定义的拦截器栈 该自定义的拦截器栈引用了struts2的默认拦截器栈和上面自定义的拦截器-->
<interceptor-ref name="defaultStack"></interceptor-ref><!--struts2默认的拦截器栈-->
<interceptor-ref name="myinterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="list_*" class="com.leeket.action.HelloAction" method="{1}">
<interceptor-ref name="myinterceptorStack"></interceptor-ref> <!--指定一个action 的拦截器,由于指定拦截器后会使得action失去struts2自带的拦截器,所以在前面要做处理,这里使用了拦截器栈-->
</action>