拦截器的实现分3个步骤:
1,定义实现上述接口的拦截器类(com.opensymphony.xwork2.interceptor.Interceptor 或者继承AbstractInterceptor)
2,在struts.xml中定义这个拦截器
3,在需要使用拦截器的Action中引用拦截器
2.
代码:
public class LoginInterceptor implements Interceptor{
private static final long serialVersionUID = 1L;
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("进入拦截器");(拦截器相关的操作)
String re = invocation.invoke();
return null;
}
在Struts中配置:
<interceptors>
<interceptor name="actionIntercept" class="interceptor.LoginInterceptor"></interceptor>
</interceptors>
同时可以拦截器栈进行一组拦截器的配置:
<interceptor-stack name="systemInterceptorStack">
<interceptor-ref name="userAuthorityInterceptor" />
<interceptor-ref name="exceptionInterceptor" />
</interceptor-stack>
此放在<interceptors></interceptors>之间,在所含有的拦截器之后。
拦截器的配置范围:
1.某一个action中
<action name="login" class="login" method="login">
<result name="success">success.jsp</result>
<interceptor-ref name="actionIntercept"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref> 如果使用拦截器则必须添加默认的拦截器
</action>
2.全局拦截器
将拦截器定义在一个包下:
<package name="all" extends="struts-default">
<interceptors>
<!-- 定义权限控制拦截器 -->
<interceptor name="authority"
class="akai.cost.ms.base.AuthInterceptor" />
<!-- 定义一个包含权限控制的拦截器栈 -->
<interceptor-stack name="mydefault">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="authority" />
</interceptor-stack>
</interceptors>
<!-- 定义默认拦截器 -->
<default-interceptor-ref name="mydefault" />(包下的拦截器)
</package>
其他的包继承这个包: