自定义Struts2_Interceptor

今天上午学习了一下关于如何自定义Interceptor的知识,做了一个超级简单的自定义拦截器。

自定义的拦截器代码:

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

public class InterceptorByPersonal implements Interceptor
{

private static final long serialVersionUID = 1L;

public void destroy()
{
System.err.println("InterceptorByPersonal destroy . . .");
}

public void init()
{
System.err.println("InterceptorByPersonal initializing . . .");
}

public String intercept(ActionInvocation invocation) throws Exception
{
System.err.println("InterceptorByPersonal is invoked . . .");
String result = invocation.invoke();
return result;
}

}


struts.xml配置文件所需要的配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 引入struts框架的配置文件 -->
<include file="struts-default.xml"></include>
<package name="struts2_test" extends="struts-default">
<!-- 在配置文件中声明定义自己的拦截器InterceptorByPersonal -->
<interceptors>
<interceptor name="interceptorByPersonal"
class="com.harry.demo.interceptors.InterceptorByPersonal"></interceptor>
</interceptors>
<action name="userCase" class="com.harry.demo.actions.UsercaseAction">
<interceptor-ref name="interceptorByPersonal"/>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="timer" />
<result name="input">/index.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>



OK,基本上就是这样了,现在重新部署一下项目,发现在控制台输出了我自定义拦截器中init()方法的代码,说明拦截器在此时已经初始化了,然后我去访问上面配置文件中已经准备好的action,这时,在控制台会打印出intercept()方法中我要打印的语句,说明该方法被调用了。

接着,多访问几次该action,发现在控制台会一直输出
InterceptorByPersonal is invoked . . .

说明了拦截器在运行时,会在每次访问之前进行调用。


引申:我看了Struts2的API,该方法的介绍时这样的:
invoke

String invoke()
throws Exception

Invokes the next step in processing this ActionInvocation. If there are more Interceptors, this will call the next one. If Interceptors choose not to short-circuit ActionInvocation processing and return their own return code, they will call invoke() to allow the next Interceptor to execute. If there are no more Interceptors to be applied, the Action is executed. If the ActionProxy getExecuteResult() method returns true, the Result is also executed.

Throws:
Exception



大概意思明白,但是还是需要多理解!毕竟自己的英文水平有限。不过,我发现一点,如果我把自定义的Interceptor中的intercept方法返回值改为null,仍旧会进行传递。但是,如果在改方法中没有执行
ActionInvocation.invoke();
方法,就会出现空白页面!!!
则有趣儿的事情就发生了。当我访问action之后,页面变成空白了,什么反应都没有。这是为何呢?参照上面的API,发现这个方法的返回值似乎是在给下面的拦截器通知(或者没有其他拦截器了,就是通知调用action实例的方法了),我让其返回null,自然就啥都没了。我目前是这样认为的,就先这样吧!


修炼内功,CODING逐鹿!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值