我的struts项目结构如下:
page1-> action1-> page2-> action2-> page3

我需要在操作2中访问在第1页的输入标签中输入的值。

这是我的代码:

第1页:

<div class = "container">
    <s:form id = "idinput" method = "post" action = "idEntered">
        Enter id: <input id = "txtid" name = "txtid" type = "text" />
        <input id = "cmdsubmit" name = "cmdsubmit" type = "submit" value = "enter details" />
    </s:form>
</div>


动作1:

public class AddId extends ActionSupport {

private int txtid;
    //getter and setter

@Override
public String execute() throws Exception {
    return "success";
}


}

第2页:

<div class = "container">
    <s:form id = "formvalues" method = "post" action = "formEntered">
        <p>Your id entered is: <s:property value = "txtid" /></p>
        First name: <input id = "txtfname" name = "txtfname" type = "text" />
        Last name: <input id = "txtlname" name = "txtlname" type = "text" />
        Age: <input id = "txtage" name = "txtage" type = "text" />
        <input id = "cmdform" name = "cmdform" type = "submit" value = "submit form" />
    </s:form>
</div>


动作2:

public class AddForm extends ActionSupport {
    private String txtfname;
private String txtlname;
private int txtage;
private int txtid;
      //getters and setters

@Override
public String execute() throws Exception {

    return "success";
}


}

并显示所有内容

第3页:

<div class = "container">
    ID: <s:property value = "txtid" /><br>
    first name: <s:property value = "txtfname" /><br>
    last name: <s:property value = "txtlname" /><br>
    age: <s:property value = "txtage" />
</div>


这是我面临的问题,因为txtid显示为null,从中我推断该值未从page2传递给action2

我想出的一个解决方案是使用

<s:hidden value = "%{txtid}" name = "txtid2 />


page2中的表单中,这将允许我将txtid的值用作txtid2中的action2,但这似乎更像是一种hack,而不是实际的解决方案,因此欢迎提出其他建议。

最佳答案

在您希望将字段值从一个操作传递到另一个操作的情况下,可以配置字段的范围。只需在每个操作中将带有getter和setter的相同字段放在同一字段中,在您的情况下将为action1action2。字段名称是txtid。除了scope拦截器不包含在defaultStack中之外,您还应该在操作配置中引用它。例如

<action name="action1" class="com.package.action.AddId">
    <result>/jsp/page2.jsp</result>
    <interceptor-ref name="basicStack"/>
    <interceptor-ref name="scope">
        <param name="key">mykey</param>
        <param name="session">txtid</param>
        <param name="autoCreateSession">true</param>
    </interceptor-ref>
</action>
<action name="action2" class="com.package.action.AddForm">
    <result>/jsp/page3.jsp</result>
    <interceptor-ref name="scope">
        <param name="key">mykey</param>
        <param name="session">txtid</param>
        <param name="autoCreateSession">true</param>
    </interceptor-ref>
    <interceptor-ref name="basicStack"/>
</action>


现在,您有了带有键mykey和范围txtid的作用域。在每个动作中提供对该字段的访问器将使字段值从一个动作转移到另一个动作。在上面的示例中,basicStack是拦截器堆栈的框架,它不包括某些包含validation拦截器的拦截器。如果您的动作需要其他功能,则应该构造一个自定义堆栈或在动作配置中引用其他拦截器。

07-24 09:21