我的Struts项目结构如下:
page1
->action1
->page2
->action2
->page3
>
我需要的是在 action2
中访问我在 page1
的输入标签中输入的值。
这是我的代码:
第 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>
Action 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>
Action 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
的值用作 action2
中的 txtid2
,然而,这看起来更像是一种 hack,而不是实际的解决方案,因此欢迎任何其他建议。
最佳答案
在您希望保留从一个操作传递到另一个操作的字段值的情况下,您可以配置字段的范围。只需在每个操作中放置带有 getter 和 setter 的相同字段,在您的情况下它将是 action1
和 action2
。字段名称是 txtid
。以及scope
interceptor不包含在 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
interceptor。 .
如果您的操作需要其他功能,您应该构建自定义堆栈或在操作配置中引用其他拦截器。
关于java - 在 Struts 2 中保留多个 JSP 和 Action 之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18443956/