【问题标题】:Struts2 : Interceptor is being only one time instead of two timesStruts2:拦截器只是一次而不是两次
【发布时间】:2011-09-15 13:44:00
【问题描述】:

我正在研究 Struts2 拦截器。 我读过Struts2拦截器就像过滤器一样,它在执行Action类之前执行,在处理结果之后再执行一次(如果我错了,请纠正我),即两次

但是当我运行下面的代码时,拦截器只执行一次。 如果我犯了任何错误,请纠正我。 请在下面查看我的代码:

这是我的 Struts.xml 文件

<struts>
<constant name="struts.devMode" value="true" />
    <package name="test" extends="struts-default">
<interceptors>
 <interceptor name="loginkiran" class="vaannila.MyLoginInterCeptor" />
</interceptors>
        <action name="HelloWorld" class="vaannila.HelloWorld" method="kiran">
            <interceptor-ref name="loginkiran" />
            <result name="SUCCESS">/success.jsp</result>
        </action>
    </package>
</struts>

这是我的动作类

public class HelloWorld
{
    public HelloWorld() {
    }
    public String kiran() {
        System.out.println("iNSIDE THE aCTION CLASS");
        return "SUCCESS";
    }
}

这是我的拦截器类

public class MyLoginInterCeptor implements Interceptor {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("Destroying Interceptor");

    }

    @Override
    public void init() {

    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        HttpServletRequest request = (HttpServletRequest) ActionContext
                .getContext().get(ServletActionContext.HTTP_REQUEST);

        System.out.println("iNSIDE THE iNTERCEPTOR");

        return invocation.invoke();

    }

}

这是我的 JSP 文件:

<html>
<body>
<%
System.out.println("iNSIde THE jsp");
%>
</body>
</html>

上述代码的输出是这样的:

iNSIDE THE iNTERCEPTOR
iNSIDE THE aCTION CLASS
iNSIde THE jsp

【问题讨论】:

    标签: struts2 actioncontext


    【解决方案1】:

    拦截器不会执行两次(过滤器也不是):拦截器(和过滤器)包装操作(或 servlet/等)

    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("Before action invocation...");
        return invocation.invoke();
        System.out.println("After action invocation...");
    }
    

    【讨论】:

    • 谢谢大卫,实际上我遵循了一个说明它们将被执行两次的教程,请查看该教程的图片imageshack.us/photo/my-images/831/struts2.jpg,如果我误解了请纠正我
    • 我已经纠正了你;该图像没有直接说明它们被执行了两次——它是模棱两可的,并且不能准确地表示被拦截的嵌套性质,也不能表明拦截器在操作完成之前没有执行完毕。 (当然,除非正常流程被中断。)
    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多