Struts2 Struts 2:如果为一个Action类配置了拦截器,那么会调用拦截器多少次
我有一个关于Struts2中拦截器的问题 Struts2提供了使用拦截器控制请求的非常强大的机制。拦截器负责大部分请求处理。它们在调用操作之前和之后由控制器调用,因此它们位于控制器和操作之间。拦截器执行诸如日志记录、验证、文件上传、双重提交等任务 我在上面几行中引用了以下内容: 在本例中,您将看到如何在执行操作之前和之后调用拦截器,以及如何将结果呈现回用户 我从上面几行中得到了这个 我已经编写了一个基本拦截器,并将其插入到我的Action类中:Struts2 Struts 2:如果为一个Action类配置了拦截器,那么会调用拦截器多少次,struts2,Struts2,我有一个关于Struts2中拦截器的问题 Struts2提供了使用拦截器控制请求的非常强大的机制。拦截器负责大部分请求处理。它们在调用操作之前和之后由控制器调用,因此它们位于控制器和操作之间。拦截器执行诸如日志记录、验证、文件上传、双重提交等任务 我在上面几行中引用了以下内容: 在本例中,您将看到如何在执行操作之前和之后调用拦截器,以及如何将结果呈现回用户 我从上面几行中得到了这个 我已经编写了一个基本拦截器,并将其插入到我的Action类中: public class Intercepto
public class InterceptorAction implements Interceptor {
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Action class has been called : ");
return success;
}
}
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>
Welcome.jsp
Login.jsp
根据他们网站上的上述声明,我假设这个行操作类在控制台上被调用了两次(即在操作之前和操作之后),但它只被打印了一次
请让我知道,如果我的理解是错误的,或者该网站的作者是错误的???不花时间阅读该页面让我澄清一些事情 你在拦截器中错过了一个重要的步骤 Struts2使用一个名为ActionInvocation的对象来管理对拦截器的调用 让我们为ActionInvocation指定一个名称(invocation),并展示框架是如何开始工作的:
ActionInvocation invocation;
invocation.invoke(); //this is what the framework does... this method then calls the first interceptor in the chain.
现在我们知道拦截器可以做预处理和后处理。。。但是接口只定义了一个方法来完成拦截器的工作(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();
}
}
四元数答案的简短版本:拦截器不会“调用两次”,拦截器包装动作调用就像servlet过滤器“包围”servlet请求一样。唯一的“gotcha”是控制返回到拦截器的时间已经呈现了结果;如果要在呈现结果之前执行某些操作,则必须实现一个
PreResultListener
.Ya,谢谢我在添加这一行时理解并再次感谢。if(result.equalsIgnoreCase(“success”){System.out.println(“在操作之后”);}