2017-02-13 95 views
0

我有2个名为District和Street的实体类,在View中,表单被分配Street对象。我如何绑定Street.district.id的值?在提交我得到NullPointerExceptionSpring MVC @ModelAttribute绑定子类

查看实体和形式:

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

在提交表单我从输入和空区得到街道名称。

回答

1

您的错误是在选择。

属性

:字段= “* {district.id}”

应该在选择未在选项标记

结果:

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

@GVArt欢迎您:) – cralfaro