【发布时间】:2023-03-23 06:13:01
【问题描述】:
我是使用 struts2 框架的新手,对它有些困惑。我有一个提交给动作类的表单。我希望将提交的字段保存到客户列表中。在动作类中我声明了一个列表,定义了 getModel 方法以返回一个客户列表,在准备方法中(我不确定这是否正确)我将对象添加到列表中
JSP
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Account </title>
</head>
<body>
<h2>
Customer details
</h2>
<s:form action="AddCustomerAction" name="/example" method="post">
<h1>
<s:textfield label="Enter First Name" name="firstName" key="firstName" required="true" size="25"/>
</h1>
<h1>
<s:textfield label="Enter Last Name" name="lastName" required="true" size="25" />
</h1>
<h1>
<s:textfield label="Enter Address" name="address" required="true" size="25" />
</h1>
<h1>
<s:select value ="state" name="state" list="stateList" label="Select State" listKey="code" listValue="desc" required="true"/>
<h1>
<h1>
<s:textfield label="Enter City" name="city" required="true" size="25" />
</h1>
<h1>
<s:textfield label="Enter Zipcode" name="zipcode" required="true" size="25" />
</h1>
<h1>
<s:submit name="OK"/>
</h1>
</s:form>
</body>
动作类
package example;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import java.util.ArrayList;
import java.util.List;
public class AddCustomerAction extends ActionSupport implements ModelDriven{
private Customer customer = new Customer();
private List<Customer> customerList;
public List<Customer> getModel()
{
return customerList;
}
public String execute()
{
this.printCustomer();
return SUCCESS;
}
public void prepare(){
customerList = new ArrayList<Customer>();
customerList.add(new Customer("first", "last"));
}
private void printCustomer(){
System.out.println("First Name = "+customer.getFirstName());
System.out.println("Last Name = "+customer.getLastName());
System.out.println("Add = "+customer.getAddress());
System.out.println("State = "+customer.getState());
System.out.println("City = "+customer.getCity());
System.out.println("Zipcode = "+customer.getZipcode());
}
在操作类中,我想将表单提交的信息保存在客户列表中,这样我就可以对其进行迭代并显示数据。
当我运行它时,名字和姓氏为空(即使我输入了值)。
我的方法(按照我的方式设置 getModel() 和 prepare())是否正确?我错过了什么?
【问题讨论】:
-
尝试将此作为参考。 [Struts 2:从具有模型驱动架构的表单中更新对象列表][1] [1]:stackoverflow.com/questions/13028113/…
-
您的问题确实有很多问题。阅读 Struts2 文档,把你仍然不理解的东西,以结构化的方式组织起来,分成多个问题,然后在这里提问(或先搜索它们)。我现在可以看到: 1) 在 Struts2 中发送 - 从 / 到 JSP 接收参数; 2)发送-接收列表; 3)在prepare()方法中读取参数; 4) 手动对象实例化 5) ModelDriven 使用(这对我没用,恕我直言)...