簡體   English   中英

Spring MVC @ModelAttribute綁定子類

[英]Spring MVC @ModelAttribute bind subclasses

我在View中有2個名為District和Street的實體類,向表單分配了Street對象。 如何綁定Street.district.id的值? 在提交時,我得到NullPointerException

查看實體和形式:

 <form class="form-inline" action="#" th:action="@{/direct/api/v1/newStreet}" th:object="${street}" method="POST">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Street name"/>
            </div>
            <div class="form-group">
                <label for="district">District</label>
                <select class="form-control" id="district">
                    <option th:each="d : ${districts}" th:field="*{district.id}" th:value="${d.id}" th:text="${d.name}"></option>
                </select>
            </div>
            <button type="submit" class="btn btn-default">Save</button>

控制器:

 @RequestMapping(value = "/newStreet", method = RequestMethod.POST)
 public String newStreet(@ModelAttribute Street street){
    log.info(street.getName());
    log.info(String.valueOf(street.getDistrict().getId()));
    return "redirect:/streets";
}

在提交表單時,我從輸入中獲得街道名稱,而空地區。

您的錯誤在選擇中。

屬性

th:field =“ * {district.id}”

應該在select中而不是在option標記中

結果:

 <select class="form-control" id="district" th:field="*{district.id}">
                    <option th:each="d : ${districts}"  th:value="${d.id}" th:text="${d.name}"></option>
                </select>

暫無
暫無

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

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