概述
基本概念
Intercetor, 即为拦截器。
1) 在Struts2中,把每一个功能都用一个个的拦截器实现;用户想用struts的哪个功能的时候,可以自由组装使用。
2) Struts2中,为了方法用户对拦截器的引用,提供了拦截器栈的定义,里面可以包含多个拦截器。文件夹(文件, 文件2) 拦截器栈(拦截器,拦截器2)
3) Struts2中,如果用户没有指定执行哪些拦截器,struts2有一个默认执行的栈,defaultStack;
一旦如果用户有指定执行哪些拦截器,默认的拦截器栈就不会被执行
拦截器的设计,就是基于组件设计的应用!
拦截器配置举例
struts-default.xml文件中,定义了struts提供的所有拦截器!
1. 定义拦截器以及拦截器栈
<interceptors>
1.1 拦截器定义
<interceptor name="" class="" />
1.2 拦截器栈的定义
<interceptor-stack name="defaultStack">
引用了上面拦截器(1.1)
</interceptor-stack>
</interceptors>
2. 默认执行的拦截器(栈)
<default-interceptor-ref name="defaultStack"/>
API
|-- Interceptor 拦截器接口
|-- AbstractInterceptor 拦截器默认实现的抽象类; 一般用户只需要继承此类即可继续拦截器开发
|-- ActionInvocation 拦截器的执行状态,调用下一个拦截器或Action
自定义一个拦截器案例
步骤:
1. 写拦截器类 (看生命周期)
2. 配置
/**
* 自定义拦截器
*/
public class HelloInterceptor implements Interceptor{
public HelloInterceptor(){
System.out.println("创建了拦截器对象");
}
@Override
public void init() {
System.out.println("执行了拦截器的初始化方法");
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("2. 拦截器,业务处理-开始");
String resultFlag = invocation.invoke();
System.out.println("4. 拦截器,业务处理-结束");
return resultFlag;
}
@Override
public void destroy() {
System.out.println("销毁....");
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="hello" extends="struts-default">
<interceptors>
<interceptor name="helloInterceptor" class="cn.itcast.a_interceptor.HelloInterceptor"></interceptor>
<interceptor-stack name="helloStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="helloInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="helloStack"></default-interceptor-ref>
<action name="hello" class="cn.itcast.a_interceptor.HelloAction">
<result name="success"></result>
</action>
</package>
</struts>
拦截器执行流程
启动:
创建所有拦截器、执行init()
访问:
先创建Action,
再执行拦截器,
最后:拦截器放行,执行execute();
