简体   繁体   English

Spring MVC @ModelAttribute绑定子类

[英]Spring MVC @ModelAttribute bind subclasses

I have 2 entity classes named District and Street, in View, to form is assigned Street object. 我在View中有2个名为District和Street的实体类,向表单分配了Street对象。 How can I bind value of Street.district.id ? 如何绑定Street.district.id的值? On for submitting I get NullPointerException . 在提交时,我得到NullPointerException

View entities and form: 查看实体和形式:

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

Controller: 控制器:

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

On form submitting I get Street name from input and null District. 在提交表单时,我从输入中获得街道名称,而空地区。

Your error is in the select. 您的错误在选择中。

The attribute 属性

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

should be in the select not in the option tag 应该在select中而不是在option标记中

Result: 结果:

 <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