拦截器
拦截器(Interceptor)拦截器是struts2的核心。
配置拦截器的步骤:
1)编写实现Inteceptor接口类
2)在struts.xml文件中定义拦截器
3)在action中使用拦截器
实例操作:
1、实现Interceptor接口的TheInterceptor1
public class TheInterceptor1 implements Interceptor
{
private String test;
public String getTest()
{
return test;
}
public void setTest(String test)
{
System.out.println("setTest");
this.test = test;
}
@Override
public void destroy()
{
// TODO Auto-generated method stub
}
@Override
public void init()
{
// TODO Auto-generated method stub
System.out.println("init");
}
@Override
public String intercept(ActionInvocation invocation) throws Exception
{
// TODO Auto-generated method stub
System.out.println("before");
String result = invocation.invoke();
System.out.println(invocation.getAction().getClass());
System.out.println(result);
return result;
}
}
从以上的程序分析得,
Interceptor有三个方法,分别是
init()方法:在服务器启动的时候加载一次,并且只加载一次
destory()方法:销毁拦截器
intercept()方法:接受invocation参数,并调用invoke()方法。如果还有更多的拦截器,就会调用下一个拦截器。如果没有的话就会调用action。
2、在struts.xml中配置文件
拦截器需要配置在action的上面。
1)定义拦截器
<interceptors>
<interceptor name="TheInterceptor1" class="cn.sict.interceptor.TheInterceptor1">//name是自定义的名字
<param name="test">sict</param>
<!-- 到拦截器中寻找名字为setTest这样一个方法 -->
</interceptor></interceptors>
2)使用拦截器
在具体的action中的result下面引用拦截器
<interceptor-ref name="TheInterceptor1"></interceptor-ref>
3、运行结果
从结果可以分析出,
1)init()在服务器启动的时候加载。
2)在action之前运行,拦截了action
3)没有更多拦截器,invoke方法直接调用action。返回success
4)在拦截器中定义的初始化参数,会在程序启动后,在程序中找定义的set方法,并赋值。
注意;一旦自定义了拦截器,将其配置在action中,我们需要在action最后加上默认的拦截器栈:defaultstack
<interceptor-ref name="defaultStack"></interceptor-ref>