`

12 struts2拦截器

 
阅读更多

自己写拦截器, 要认识下面接口 与 类


com.opensymphony.xwork2.interceptor.Interceptor 接口

这是最重要的接口, 一般不直接使用它.


com.opensymphony.xwork2.interceptor.AbstractInterceptor 抽象类(空实现了Interceptor接口)

自己写拦截器 可继承这个抽象类, 重写intercept()方法. 实现对某个Action的拦截


com.opensymphony.xwork2.interceptor.MethodFilterInterceptor 抽象 类 (继承AbstractInterceptor)

自己写拦截器 可继承这个抽象类, 重写doIntercept()方法. 实现对某个Action的的某个方法的拦截.

excludeMethods(排除哪方法),includeMethods(拦截哪些方法), 多个方法名用豆号隔开.

			<interceptor-ref name="myInterceptor3">
				<param name="excludeMethods">test,execute</param>
				<param name="includeMethods">test</param>
			</interceptor-ref>




-----------------------------------

自定义拦截器 :MyInterceptor

package ssh.org.interceptor;

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

/**
 * 自定义拦截器,实现Interceptor接口
 *
 * 要是改为继承 AbstractInterceptor 抽象类,  下面destroy(),init()方法就这用写了
 */
public class MyInterceptor implements Interceptor
{

	@Override
	public void destroy()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public String intercept(final ActionInvocation actioninvocation) throws Exception
	{
		System.out.println("方法执行前插入 代码");

		//执行目标方法 (调用下一个拦截器, 或执行Action)
		final String res = actioninvocation.invoke();

		System.out.println("方法执行后插入 代码");
		return res;
	}

}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	
	<package name="struts2" extends="struts-default">
		<interceptors>
			<!-- 配置自己的拦截器 -->
			<interceptor name="myInterception" class="ssh.org.interceptor.MyInterceptor"/>
			<!-- 配置自己的拦截器栈 -->
			<interceptor-stack name="myInterceptionStack">
								
				<!-- 加入默认的拦截器栈 -->
				<interceptor-ref name="defaultStack"></interceptor-ref>
				<interceptor-ref name="myInterception"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		
		<!--用户  -->
		<action name="user_*" class="ssh.org.web.UserAction" method="{1}">
			<result name="success">/user/success.jsp</result>
			<result name="input">/user/user.jsp</result>
			<!-- 应用我自己的拦截器 -->
			<interceptor-ref name="myInterceptionStack"/>
		</action>	
	</package>
</struts>

----------------------------------------------------------------------

在struts2-core-2.1.2.jar 包中 , 根目录有一个struts-default.xml 定义默认拦截器: <default-interceptor-ref name="defaultStack"/>

内有大量的拦截器, 我们要扩展, 比如 :

<interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>
<interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>

---------------------------------------------------------------------

附件中有 eclipse3.3 工程源码, 写的有点乱, 对付看吧.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics