我的struts项目结构如下: page1-> action1-> page2-> action2->page3
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
txtid
null
我想出的一个解决方案是使用
<s:hidden value = "%{txtid}" name = "txtid2 />
以page2允许我使用txtidas txtid2中的值的形式action2,这似乎更像是hack,而不是实际的解决方案,因此欢迎其他建议。
txtid2
在您希望将字段值从一个操作传递到另一个操作的情况下,可以配置字段的范围。只需在每个操作中将带有getter和setter的相同字段放在同一个字段中,在您的情况下将为action1and action2。字段名称为txtid。除scope拦截器未包含在其中外,defaultStack您还应在操作配置中引用它。例如
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。在每个动作中提供对该字段的访问器将使字段值从一个动作转移到另一个动作。在上面的示例中,basicStackwhich是拦截器堆栈的框架,它不包括某些包含validation拦截器的拦截器。如果您的动作需要其他功能,则应该构造一个自定义堆栈或在动作配置中引用其他拦截器。
mykey
basicStack
validation