首页 > 解决方案 > 如何在 Thymeleaf 中提交二维数组?

问题描述

我正在尝试提交包含两个维度数组的表单。你能检查我的代码并告诉我它有什么问题吗?

形式:

public class SimpleForm {

    private String[][] twoDimentionArray;

    public String[][] getTwoDimentionArray() {
        return twoDimentionArray;
    }

    public void setTwoDimentionArray(String[][] twoDimentionArray) {
        this.twoDimentionArray = twoDimentionArray;
    }
}

百里香叶:

<form action="#" th:action="@{/save-form} th:object="${form}" method="post"> 

    <input type="text" th:field="*{twoDimentionArray[0][0]}"/>

    <input type="submit" value="Submit" />

</form>

出现以下错误:

java.lang.IllegalArgumentException: array element type mismatch
    at java.lang.reflect.Array.set(Native Method) ~[na:1.8.0_171]
    at org.springframework.beans.AbstractNestablePropertyAccessor.processKeyedProperty(AbstractNestablePropertyAccessor.java:311) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:275) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:839) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.validation.DataBinder.doBind(DataBinder.java:735) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:197) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:107) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.bindRequestParameters(ServletModelAttributeMethodProcessor.java:157) ~[spring-webmvc-5.0.4.RELEASE.jar:5.0.4.RELEASE]

标签: javaspring-bootthymeleafsubmit

解决方案


你传递你的数组错误。尝试这个

<form action="#" th:action="@{/save-form}" th:object="${form}" method="post"> 
    <div th:each="1d, i: *{twoDimentionArray}">
        <div th:each="test, j: *{1d}">
            <input type="text" th:field="*{userAddresses[__${i.index}__][__${j.index}__]}" />
       </div>
    </div>

    <input type="submit" value="Submit" />

</form>

推荐阅读