struts2拦截器简介

来源:互联网 发布:淘宝野模 编辑:程序博客网 时间:2024/05/17 11:35

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) throwsException

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处理类.

0 0