java - 无法在 spring mvc 中获取 thymeleaf 表单数据

标签 java spring-mvc thymeleaf

我是 Thymeleaf 的新手,我尝试使用 Thymeleaf 和 Spring MVC 执行一个简单的表单提交示例。我根据 Thymeleaf 文档编写了代码。但是我在 Controller 中得到空值。

<form action="thymeleafexample/thymeleaf.html" th:action="@{/thymeleaf}"
      th:object="${loginModel}" method="post">
    <table>
        <tr>
            <td th:text="#{emp.empId.label}">Emp ID</td>
            <td><input type="text" th:field="*{empId}"/></td>
        </tr>
        <tr>
            <td th:text="#{emp.empName.label}">Emp Name</td>
            <td><input type="text" th:field="*{empName}"/></td>
        </tr>
        <tr>
            <td>
                <button type="submit" name="save" th:text="#{${'.emp.button.label'}}">submit</button>
            </td>
        </tr>
    </table>
</form>

我的 Controller 是

@RequestMapping(value = "/thymeleaf", params = {"save"})
public String save(@Validated LoginModel loginModel, final BindingResult bindingResult, ModelMap model) {
    if (bindingResult.hasErrors()) {
        return "thymeleaf";
    }
    System.out.println(loginModel);
    System.out.println(loginModel.getEmpName());
    return "/thymeleaf";
}

我的模型类是

public class LoginModel {

    private String empName;
    private int empId;

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public int getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }
}

最佳答案

我遇到了同样的问题 as OP mentioned ,为具有必要成员字段的 POJO(Model) 类创建构造函数并使用 th:field=*{foo} 而不是 th:value=${foo} 解决了我的问题。

关于java - 无法在 spring mvc 中获取 thymeleaf 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671221/

相关文章:

java - 正则表达式组成

java - Tomcat servlet 应用程序的后台线程

postgresql - 带有 postgres 和 tomcat8 的 Spring MVC

java - Spring 3拦截器错误: Type Element type "beans" must be followed by either attribute specifications, ">"或 "/>"

java - SpringTemplateEngine.process不读取文件(thymeleaf)

java - Spring MVC/Thymeleaf - 如何使用一个输入字段插入两个不同的表?

java - 无法使用 Thymeleaf 解析 View

java - 如何求解二变量线性联立方程? java

Spring Data JPA Java 配置 HibernatePersistence.class

java - Spring 和 thymeleaf 以 html 作为资源