008-Struts2框架拦截器一

这里主要记录一下拦截器。

Struts2里的拦截器interceptor类似于Servlet里的过滤器filter,如果加入拦截器,则struts2的一般流程(不包含其他情况)为:

服务接收到客户端请求----》查看web.xml文件,进入struts2控制----》查看struts.xml文件----》进入拦截器 ---》进行类型转换converter----》执行action类的set方法----》执行验证框架----》执行验证类----》执行action类里的validate方法----》执行action类里的execute方法-----》退出拦截器

现在来编写一个简单的说明例子。

1、新建一个包com.xbb.interceptor,在该包下新建一个类FirstInterceptor,让其实现Interceptor接口:

package com.xbb.interceptor;

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

public class FirstInterceptor implements Interceptor {

	private String testparam;
	
	public String getTestparam() {
		return testparam;
	}

	public void setTestparam(String testparam) {
		this.testparam = testparam;
	}

	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("firstinterceptor detory");
	}

	public void init() {
		// TODO Auto-generated method stub
		System.out.println("first interceptor init");
		System.out.println("init testparam:"+ testparam);
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("first intercept()");
		String result = invocation.invoke();
		System.out.println("first result:" + result );
		//System.out.println("intercept testparam:"+ testparam);
		return result;
	}

}

2、在struts.xml里配置拦截器,分两步:

------2.1声明拦截器:

<interceptors>
      <interceptor name="firstInterceptor" class="com.xbb.interceptor.FirstInterceptor">
              <param name="testparam">xbb</param>
      </interceptor>
</interceptors>

其中<param>子元素存放参数,只要在拦截器类里定义相应的set方法,就能在初始化拦截器时自动获取参数。

-----2.2使用拦截器:

<action name="docommit" class="com.xbb.action.DoCommit">
       <result name="success">/result.jsp</result>
       <result name="input">/commit.jsp</result>
       <interceptor-ref name="firstInterceptor"></interceptor-ref>
       <interceptor-ref name="defaultStack"></interceptor-ref>
</action>

defaultStack是启用struts默认的拦截器栈。

至此完毕。尴尬





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值