簡體   English   中英

無法在Spring MVC中獲取百里香表格數據

[英]Unable to get thymeleaf form data in spring mvc

我是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";
}

我的Model課是

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

我遇到了同樣的問題, 正如OP所述 ,使用必要的成員字段為POJO(Model)類創建構造函數,並使用th:field=*{foo}而不是th:value=${foo}解決了我的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM