下面的代碼應該生成一個文本輸入的表格,其中給定的2d字符串數組的維度指定爲ModelAttribute
。另外,每個輸入的佔位符都是它在數組中的相應值。然後用戶輸入他們自己的文本值,並且在按下「提交輸入」時,這些值按順序輸出,以空格分隔。Spring MVC Thymeleaf錯誤:數組元素類型不匹配
InputHolder.java
public class InputHolder {
private String[][] input;
public String[][] getInput() {
return input;
}
public void setInput(String[][] input) {
this.input = input;
}
}
GreetingController.java
public class GreetingController {
@ModelAttribute("string2d")
public String[][] make2dStringArray() {
return new String[][] {{"The", "quick", "brown"}, {"fox", "jumps", "over"}, {"the", "lazy", "dog."}};
}
@RequestMapping(value="/greeting")
public String recieveInput(final InputHolder inputHolder, Model model) {
if (inputHolder == null || inputHolder.getInput() == null)
return "greeting";
String output = "";
for (String[] row : inputHolder.getInput())
for (String str : row)
output += " " + str;
model.addAttribute("output", output);
return "greeting";
}
}
greeting.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="/greeting" th:object="${inputHolder}" method="POST">
<table>
<tr th:each="row,rowStat : ${string2d}">
<td th:each="string,stringStat : ${row}">
<input type="text" th:field="*{input[__${rowStat.index}__][__${stringStat.index}__]}" th:placeholder="${string}" />
</td>
</tr>
</table>
<button type="submit" name="submitInput">Submit Input</button>
</form>
<p th:text="'Output:' + ${output}"></p>
</body>
</html>
一切正常,直到我按下「提交輸入」,在這一點上,我得到以下錯誤:
java.lang.IllegalArgumentException: array element type mismatch at java.lang.reflect.Array.set(Native Method)
儘管這顯然是一個Java端的錯誤,該錯誤信息是不是給我一個發生錯誤的特定行號,並且在錯誤發生時也不會在調試模式下暫停。我不知道爲什麼會出現這個特定的錯誤,因爲在我看來,我的對象類型(字符串,字符串數組,2d字符串數組)在我的代碼中是一致的/正確的,再加上我說我不知道在哪裏據推測發生了錯誤。