【java学习之旅】——Struts2自定义拦截器三部曲

【前言】

    拦截器(interceptor)是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。通常Struts的功能中有AOP作用,其中拦截器是实现AOP的一种策略。

【内容】

1.编写实现interceptor接口类:接口类中destroy和init方法并不重要,重要的是intercept方法,其中ActionInvocation参数的invoke调用方法是告诉Struts接下来要做的事情。

public class TheInterceptor1 implements Interceptor {

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

	}

	public void init() {
		//服务器启动的时候运用拦截器 ! 
		System.out.println("init invoked!");

	}

	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("before");
		System.out.println(arg0.getClass());
		String result=arg0.invoke();
		System.out.println("after");
		return result;
	}

}
2.Struts.xml中配置定义的拦截器

<package name="struts2" namespace="/" extends="struts-default">

 <interceptors>
    <interceptor name="theInterceptor1" class="com.cyl.interceptor.TheInterceptor1"></interceptor>
 </interceptors> 
</package>
</struts>

3.在action中使用拦截器

<action name="token" class="com.cyl.struts2.TokenAction">
      <result name="success">/tokenSuccess.jsp</result>
     
      <result name="input">/token.jsp</result>
      <interceptor-ref name="theInterceptor1"></interceptor-ref>
      <interceptor-ref name="defaultStack"></interceptor-ref>
     </action>
注:

   一旦定义了自己的拦截器,要将其配置到action之后,在action的最后要添加上默认拦截器栈:defaultStack,否则默认的拦截器就会不起作用。Struts的默认拦截器参考:http://blog.csdn.net/getchance/article/details/7982251

【总结】

     拦截器(interceptor)是Struts2最强大的特性之一,也可以说是struts2的核心,拦截器可以让你在Actionresult被执行之前或之后进行一些处理。其实拦截器和之前学的filter(过滤器)非常的像,但是有一些区别,将在后面的文章做简单介绍!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值