一、拦截器简介
拦截器是在访问Action之前/之后 进行拦截的,并且拦截器可插拔(添加/去除)的。
优点:通用功能的封装,提供了可重用性。
二、预定义拦截器 和 拦截器栈
预定义拦截器 和 拦截器栈 在struts-default.xml中有定义
interceptor interceptor-stack
定义一个拦截器:
public class Myintercetor implements Interceptor{
@Override
public void destroy() {
System.out.println("Myintercetor destroy");}
@Override
public void init() {System.out.println("Myintercetor init"); }
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Myintercetor intercept,action执行之前");
String result = invocation.invoke();//执行action
//result为action的返回值
System.out.println("Myintercetor intercept,action执行之后");
return result;
}
注册与引用拦截器
<struts>
<package name="helloworld" extends="struts-default">
<!--定义拦截器 -->
<interceptors>
<interceptor name="Myintercetor" class="interceptor.Myintercetor"></interceptor>
</interceptors>
<action name="hello" class="action.hellowrod">
<result name="success">helloword.jsp</result>
<!--引用拦截器 ,访问按上下的顺序执行的 -->
<interceptor-ref name="Myintercetor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package>
</struts>
<!--定义拦截器 -->
<interceptors>
<interceptor name="Myintercetor" class="interceptor.Myintercetor"></interceptor>
<interceptor name="Loginintercetor" class="interceptor.Loginintercetor"></interceptor>
<!--定义拦截器栈 -->
<interceptor-stack name="MyStack">
<interceptor-ref name="Loginintercetor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!--设置默认拦截器栈,当有写名拦截器是不使用这个-->
<default-interceptor-ref name="MyStack"></default-interceptor-ref>