1.struts2的拦截器有三种
默认拦截器,模型驱动拦截器,自定义拦截器
2.自定义拦截器的步骤
2.1 先建立一个普通类,继承于AbstractIntercept,实现intercept方法。
public class helloAction5 {
public String sayhello(){
System.out.println("HellAction方法执行了");
return "success";//与struts.xml配置文件中的name取值一致
}
}
public class demoInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO 自动生成的方法存根
System.out.println("拦截器执行了,动作方法之前");
String rtvalue = invocation.invoke();
System.out.println(rtvalue);
System.out.println("拦截器执行了后");
return null;
}
}
2.2,在strut.xml中需要配置默认拦截器,然后在action中使用该拦截器
<interceptors>
<interceptor name="demoInterceptor" class="com.itheima.web.action.demoInterceptor"></interceptor>
</interceptors>
<action name="sayhello" class="com.itheima.web.action.helloAction5" method="sayhello">
<!-- 使用自定义拦截器 -->
<interceptor-ref name="demoInterceptor"></interceptor-ref>
<result name="success">/success.jsp</result>
</action>
<interceptors> 用来声明自定义的拦截器
</interceptors>
<action>
<interceptor-ref name ="">
</interceptor-ref<action>
3.分析struts2的执行过程
从上图中可以看出,浏览器请求之后,先经过actionproxy后到达拦截器,拦截器拦截后进入到action,再经过result结果视图,然后把结果视图送到Template
然后再返回到拦截器,再经过HttpServletRespose返回给浏览器。
对于存在多个拦截器的话,执行顺序与声明的顺序无关。