gpt4 book ai didi

java - 通过 Spring 根据请求填充集合?

转载 作者:行者123 更新时间:2023-11-29 09:24:56 25 4
gpt4 key购买 nike

我有一个可以输入购买的页面,以及购买的所有 foos。我在一个 html 文档中得到了三个元素,它们被解析为逗号分隔的格式。

function submitStuff()
{
//grab each cells value from dynamically built table based on user entries
//appending comma
document.form.ids.value=Ids;
document.form.price.value=prices;
document.form.qtys.value=qtys;
document.form.submit();
}

一旦分解,每个 id/price/qty 应该填充到一个对象中......

public class foo{ 
private int id;
private BigDecimal price;
private int qty;
//set&get;
}

它可以作为另一个对象的集合...

public class purchase{
private Date date;
private int buyId;
private List<foo> purchases;
//set&get;
}

我知道我可以获取请求参数并一个一个地构建 foo 对象。我认为有一种更好的方法可以在对购买对象执行数据绑定(bind)时填充该列表,因为它可以正确填充所有其他属性。

最佳答案

除了将参数连接成一个单独的逗号分隔参数并在服务器端将其拆分(老实说,这是一种漂亮的 nasty 方法),您还可以只使用相同的参数名称发送多个参数值。然后它将作为 String[] 数组由 HttpServletRequest#getParameterValues() 提供。在参数名称上。

我不使用 Spring,所以这里有一个普通的 HTML/Servlet 示例来说明这个想法:

<table>
<tr>
<td>ID: 12<input type="hidden" name="id" value="12"></td>
<td>Qty: <input type="text" name="qty"></td>
<td>Price: $100.00<input type="hidden" name="price" value="100.00"></td>
</tr>
<tr>
<td>ID: 54<input type="hidden" name="id" value="54"></td>
<td>Qty: <input type="text" name="qty"></td>
<td>Price: $200.00<input type="hidden" name="price" value="200.00"></td>
</tr>
<tr>
<td>ID: 8<input type="hidden" name="id" value="8"></td>
<td>Qty: <input type="text" name="qty"></td>
<td>Price: $500.00<input type="hidden" name="price" value="500.00"></td>
</tr>
</table>

小服务程序:

String[] ids = request.getParameterValues("id");
String[] qtys = request.getParameterValues("qty");
String[] prices = request.getParameterValues("price");

for (int i = 0; i < ids.length; i++) {
Long id = Long.parseLong(ids[i]);
Integer qty = Integer.parseInt(qtys[i]);
BigDecimal price = new BigDecimal(prices[i]);
// ...
}

然而,我非常质疑是否需要将价格也从客户端发送到服务器。我宁愿(重新)计算服务器端的价格,因为客户端可以完全控制它发送的请求参数,因此能够在您的表单控制之外更改参数值。

关于java - 通过 Spring 根据请求填充集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com