以下代码应生成一个文本输入表,其中给定的2d字符串数组的维度指定为ModelAttribute
。此外,每个输入的占位符都是其在数组中的相应值。然后用户输入他们自己的文本值,并在按下“提交输入”时按顺序输出这些值,用空格分隔。
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:数组元素类型不匹配 at java.lang.reflect.Array.set(Native Method)
尽管这显然是Java端错误,但错误消息并未给出错误发生的特定行号,并且在发生错误时也不会在调试模式下暂停。我不知道为什么会出现这个特定错误,因为在我看来我的对象类型(字符串,字符串数组,2d字符串数组)在我的代码中是一致/正确的,加上我说我不知道究竟在哪里据说错误正在发生。
答案 0 :(得分:1)
好吧,我发现了错误......我忘了实例化InputHolder
的{{1}}字段。
虽然严重无益的调试。没有“类型不匹配”; “空指针”或“数组索引越界”怎么样?行号本来也不错。