拦截器
1. 定义拦截器:
1.1 要实现com.opensymphony.xwork2.interceptor.Interceptor, 但是通常继承
com.opensymphony.xwork2.interceptor.AbstractInterceptor, 因为init destroy 通常用不到,如果用到了就覆盖..
public class MyInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("这是我的拦截器");
return invocation.invoke(); //一定要调用该方法进行去调用其他的拦截器或者是Action
}
}
1.2 配置拦截器:
在struts.xml的包中配置拦截器
<interceptors>
<interceptor name="MyInterceptor" class="cn.itcast.cd.interceptor.MyInterceptor"></interceptor>
</interceptors>
<action name="hello" class="cn.itcast.cd.action.HelloAction">
<interceptor-ref name="MyInterceptor"></interceptor-ref>
<result>/success.jsp</result>
</action>
1.3 如果在一个包自己定义了默认拦截器, 那么将会覆盖父包中的默认的拦截器
如果在Action中没有定义拦截器的话就使用默认的拦截器
如果Action中使用到多个拦截器的话,可以把拦截器组成一个拦截器栈. 定义好的拦截器栈也可以合并到其他的拦截器栈中..
拦截器范例:
<package name="day2" extends="struts-default">
<interceptors>
<!-- 定义单个拦截器 -->
<interceptor name="MyInterceptor" class="cn.itcast.cd.interceptor.MyInterceptor">
<param name="username">张三</param>
</interceptor>
<interceptor-stack name="MyInterceptor_stack">
<interceptor-ref name="MyInterceptor"></interceptor-ref>
<!-- 可以把已经定义好的拦截器栈合并到当前拦截器栈中.. -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 用注解方式实现拦截器, 它可以让加上注解的方法执行... -->
<interceptor-ref name="annotationWorkflow"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 定义默认的拦截器 -->
<action name="hello" class="cn.itcast.cd.action.HelloAction">
<interceptor-ref name="MyInterceptor_stack"></interceptor-ref>
<!-- 在Action中没有定义拦截器将会使用默认的拦截器 -->
<result>/success.jsp</result>
</action>