2

我正在研究 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
4

1 回答 1

3

Interceptors are not executed twice (nor are filters): interceptors (and filters) wrap the action (or servlet/etc.)

public String intercept(ActionInvocation invocation) throws Exception {
    System.out.println("Before action invocation...");
    return invocation.invoke();
    System.out.println("After action invocation...");
}
于 2011-09-15T14:16:39.610 回答