我有一个 jsp/html 表单,它收集用户的一系列选择。例如,我问“你喜欢这种食物的什么?”用户可以为每个输入字段添加 1 个答案(可以选择输入无限数量的选项)。 html 如下所示:
<li><input type="text" name="choiceList[]" /></li>
<li><input type="text" name="choiceList[]" /></li>
<li><input type="text" name="choiceList[]" /></li>
<li><input type="text" name="choiceList[]" /></li>
<li><input type="text" name="choiceList[]" /></li>
...
在我的后端(使用 Spring)中,我将 choiceList 数组分配给 String[] Choices
java 数组。
我的问题是,如果有人在一个输入字段中放置一个逗号分隔的列表(例如:apple,mango,orange”)并在另一个输入字段中放置“pineapple”,则支持的java数组会认为用户输入是 4 个单独的项目(苹果、芒果、橙子、菠萝),因为 html 表单数组 choiceList[]
基本上是一个逗号分隔的列表。
我需要在表单中做什么才能真正知道用户只填写了 2 个输入字段?更清楚地说,我希望我的 java 数组的大小为 2,而不是大小 4。
最佳答案
您可以使用@InitBinder annotation配置字符串数组的绑定(bind):
@InitBinder("choiceList")
public void fqBinderInit(WebDataBinder b) {
b.registerCustomEditor(String[].class, new StringArrayPropertyEditor("&"));
}
关于java - 如何在jsp中传递逗号分隔的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10075260/