【问题标题】:Unable to get thymeleaf form data in spring mvc无法在 spring mvc 中获取 thymeleaf 表单数据
【发布时间】:2014-07-10 07:55:48
【问题描述】:

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

<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>

我的控制器是

@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;
    }
}

【问题讨论】:

  • Emp ID
    Emp Name
  • 你的控制器方法真的被正确调用了吗?
  • 感谢您的回复,是的,它的调用正确。
  • 尝试删除 params={"save"} 并告诉我
  • 我试过了,结果还是一样

标签: java spring-mvc thymeleaf


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2016-03-14
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多