Struts2.1拦截器原理以及相关的配置



Struts2.1拦截器原理以及相关的配置。

7.1拦截器实现原理
7.2拦截器配置初步
7.2.1 struts.xml文件中定义拦截器
格式:
<interceptor name=”拦截器名”class=”拦截器实现类”></interceptor>
拦截器栈:多个拦截器连在一起组成拦截器栈。
格式:
<!– 拦截器栈 –>
<interceptor-stack name=”拦截器栈名”>
<interceptor-ref name=”拦截器1″></interceptor-ref>
<interceptor-ref name=”拦截器2″></interceptor-ref>
<interceptor-ref name=”拦截器3″></interceptor-ref>
</interceptor-stack>
7.2.2 使用拦截器 通过<interceptor-ref …/>元素可以在Action内使用拦截器。
7.2.3 配置默认拦截器
默认拦截器何时起作用?
没有显示指定拦截器时,则默认的拦截器会起作用
配置默认拦截器:<default-interceptor-ref…/>元素,该元素作为<package…/>
元素的子元素使用。
格式:<default-interceptor-ref name=”拦截器名或拦截器栈名”/>
7.2.4 Struts2内建的拦截器
关于内建的拦截器可查看struts-default.xml文件

7.2.5 与拦截器相关的配置元素
<interceptors…/>
<interceptor…/>
<interceptor-stack…/>
<interceptor-ref…/>
<param…/>
<default-interceptor-ref…/>:
7.3 开发自己的拦截器
开发自己的拦截器类要实现com.opensymphony.xwork2.interceptor.Interceptor接口。
实现类代码如下:
package com.test.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyInterceptor implements Interceptor {

@Override
public void destroy() {
System.out.println(“destroy”);

}


@Override
public void init() {
System.out.println(“init”);

}

@Override
public String intercept(ActionInvocation invo) throws Exception {
System.out.println(“myInterceptor”);
String result = invo.invoke();
return result;
}

}
7.3.1使用拦截器
配置文件如下:
<?xml version=”1.0″ encoding=”GBK”?>
<!– 指定Struts 2配置文件的DTD信息 –>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.1//EN”
“http://struts.apache.org/dtds/struts-2.1.dtd”>
<!– struts是Struts 2配置文件的根元素 –>
<struts>
<constant name=”struts.custom.i18n.resources” value=”message”></constant>
<package name=”Struts2″ extends=”struts-default”>
<!– 定义 –>
<interceptors>
<interceptor name=”myInterceptor”
class=”com.test.interceptor.MyInterceptor”>
</interceptor>
<!– 拦截器栈 –>
<interceptor-stack name=”myStack”>
<interceptor-ref name=”myInterceptor”></interceptor-ref>
<interceptor-ref name=”defaultStack”></interceptor-ref>
</interceptor-stack>
</interceptors>
<!– 配置默认拦截器–>
<default-interceptor-ref name=”myStack”></default-interceptor-ref>

<action name=”Register”
class=”com.test.action.RegisterAction”>

<result name=”success”>/Success.jsp</result>
<result name=”input”>/s_Register.jsp</result>
<!– <interceptor-ref name=”myInterceptor”></interceptor-ref>
<interceptor-ref name=”defaultStack”></interceptor-ref>
–>
<!– <interceptor-ref name=”myStack”></interceptor-ref> –>
<!–使用默认拦截器 –>
</action>
</package>
</struts>

http://blog.csdn.net/java_cxrs/article/details/4652345