我有以下豆子:
class User {
private List<Address> addresses;
// ... getter and setter for addresses follows
}
class Address {
private String street, city;
// ... getters and setters follows
}
这是控制器
@RequestMapping(value = { "/doSomething" })
public String doSomething(@ModelAttribute User user, BindingResult result, Model model) {
// ...
}
表格可能类似
<form>
<input type="text" name="addresses[].street" />
<input type="text" name="addresses[].city" />
...
</form>
但是我收到以下错误
Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'addresses[]' of bean class [User]: Invalid index in property path 'addresses[]'; nested exception is java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_31]
at java.lang.Integer.parseInt(Integer.java:592) ~[na:1.8.0_31]
at java.lang.Integer.parseInt(Integer.java:615) ~[na:1.8.0_31]
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:989) ~[spring-beans-4.1.2.RELEASE.jar:4.1.2.RELEASE]
如何命名表单中的字段以便Spring能够进行绑定?
答案 0 :(得分:0)
我认为错误是因为它无法将[“”]转换为[number],因此无法找到它应该访问的数组中的哪个元素。
对于集合,您可以使用ngRepeat循环或使用显式索引。在大多数情况下,你会想要循环,所以这是一个例子:
<form ng-repeat="address in user.addresses">
<input type="text" ng-model="address.street" />
<input type="text" ng-model="address.city" />
...
</form>
请注意,如果您使用angular提交表单,则此方法有效(因此,您可以提交Angular正在修改的范围对象,而不是允许标准HTML提交。
答案 1 :(得分:0)
我明白了。问题是该属性缺少索引。 Spring可以绑定多个属性(集合,列表,数组)来请求参数,但名称必须包含索引。
所以表格必须是
import java.util.Random;
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
int guess = 0;
int tries = 3;
Scanner input = new Scanner(System.in);
Random ran = new Random();
int diceNumber = ran.nextInt(6) + 1;
System.out.println(diceNumber);
System.out.println("Insert a number between 1 and 6 : you have "
+ tries + " tries.");
guess = input.nextInt();
loop: while ((tries >= 1)) {
--tries;
if ((guess >= 7 || guess <= 0) && (tries >= 1)) {
System.out.println("Number out of range, try again; you have "
+ tries + " more tries.");
guess = input.nextInt();
} else {
if (guess == diceNumber) {
System.out.println("You Win!!");
break loop;
} else if (tries >= 1) {
System.out.println("Incorrect Number, you have " + tries
+ " more tries.");
guess = input.nextInt();
}
}
}
if (tries == 0 && guess != diceNumber) {
System.out.println("You Lose!!");
}
}
}
而不是<form>
<input type="text" name="addresses[0].street" />
<input type="text" name="addresses[0].city" />
<input type="text" name="addresses[1].street" />
<input type="text" name="addresses[1].city" />
...
</form>
,0
...您可以在Thymeleaf(服务器端)使用1
或在Angular(客户端)使用${iterationStatus.index}
。