struts2拦截器简介

Struts2拦截器,

Intorduction:


WorkFlow:

1:框架首先寻找这个请求对应的Action,以及和这个Action有关的Interceptor


2:Framework创建一个ActionInvocation的实例并调用Invoke()方法.此时,Framework已经吧控制权交给了ActionInvocation对请求做进一步的处理;


3:ActionInvocation就是封装(encapsulates)action及其相关interceptors的类;ActionInvocation知道Interceptor的调用顺序;


4:ActionInvocation调用栈中第一个interceptorintercept()方法.(我们将会在实例的帮助下理解这个,实例很简单,只使用了interceptor记录日志)


5:LoggingInterceptorintercept()方法包含以下代码:

01.publicString intercept(ActionInvocationinvocation) throws Exception

02.{

03.//Preprocessing

04.logMessage(invocation,START_MESSAGE);

05. 

06.Stringresult = invocation.invoke();

07. 

08.//Postprocessing

09.logMessage(invocation,FINISH_MESSAGE);

10. 

11.returnresult;

12.}



6:正如你所看到的,首先logMessage()方法被调用,message被记录,这个是被loggerinterceptor唆处理完成的.然后ActionInvocationinvoke()方法再一次被调用,这一次,我们可以调用栈中的下一个interceptor,而且这个循环会持续到栈中的最后一个interceptor.


7:完成所有的interceptors之后,action类会被调用,最后返回一个字符串结果,对应的视图将会被渲染.这个是正常的工作流.


8:但是如果validation出现错误,这种情况下,请求处理将会被终止,不会在调用其他的interceptor.Action也不会被执行.控制流程就会改变....Thecontrol flow changes, now the interceptors executed so far will beinvoked in the reverse order to do the post processing if any andfinally the result will be rendered to the user.


9:回归到正常的工作流,在我们的例子中,loggerinterceptor是唯一一个在栈中的interceptor,所以在记录START_MESSAGE之后,ActionInvocationinvoke()方法将会被调用这个action,action仅仅返回一个”sucess”,然后,loggerinterceptor将会做之后的处理,这一次,FINISH_MESSAGE将会被记录下来,结果将会被返回.基于结果的视图将会渲染给用户.


我们可以获得如下好处,通过使用interceptor;

*极大的灵活性;

*专注于Actionclasses;(clear and focused Action classes)

*提高代码可读性和重用性;

*测试过程变得很简单

*我们可以通过添加interceptor到栈中,定制对每一个请求有效的action处理类.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值