我对Struts2中的拦截器有疑问
Struts2提供了非常强大的使用拦截器控制请求的机制.拦截器负责大多数请求处理.它们在调用动作之前和之后由控制器调用,因此它们位于控制器和动作之间.拦截器执行记录,验证,文件上传,双提防等任务.
我从以上几行开始:
http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html
在此示例中,您将看到在执行操作之前和之后如何调用拦截器以及如何将结果呈现给用户.
我已经采取了以上这些线
http://www.vaannila.com/struts-2/struts-2-example/struts-2-interceptors-example-1.html
我编写了一个基本的拦截器并将其插入我的Action类:
public class InterceptorAction implements Interceptor {
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Action class has been called : ");
return success;
}
}
Run Code Online (Sandbox Code Playgroud)
在struts.xml
<action name="login" class="com.DBAction">
<interceptor-ref name="mine"></interceptor-ref>
<result name="success">Welcome.jsp</result>
<result name="error">Login.jsp</result>
</action>
Run Code Online (Sandbox Code Playgroud)
根据他们网站上面的语句,我假设已经在控制台上调用了这一行Action类两次(那是在Action之前和Action类之后),但是它只打印了一次?
请告诉我,如果我的理解是错误的,或者作者在那个网站上错了?
没有花时间阅读页面让我们清楚一些事情......
你错过了拦截器中的重要一步.
Struts2使用一个名为ActionInvocation的对象来管理调用拦截器.
让我们给ActionInvocation一个名称(调用),并展示框架如何开始滚动:
ActionInvocation invocation;
invocation.invoke(); //this is what the framework does... this method then calls the first interceptor in the chain.
Run Code Online (Sandbox Code Playgroud)
现在我们知道拦截器可以进行预处理和后处理......但是接口只定义了一个方法来完成拦截器的工作(init和delete只是生命周期)!如果界面定义了doBefore和doAfter它会很容易,所以必须有一些魔法,发生......
事实证明,你负责在拦截器的某个点上将控制权交还给动作调用.这是一项要求.如果不将控制权交还给ActionInvocation,则会破坏链.
因此,在创建拦截器时,请执行以下步骤
这是一个完整但无用的例子:
package com.quaternion.interceptors;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor{
@Override
public void destroy() {
//nothing to do
}
@Override
public void init() {
//nothing to do
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Something to do before the action!");
String resultString = invocation.invoke();
System.out.println("Something to do after the action!");
return resultString;
//if you are not doing post processing it is easiest to write
//return invocation.invoke();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3434 次 |
| 最近记录: |