我有以下课程:
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
private int personId;
@Column(name = "person_name", unique = true)
private String personName;
@Column(name = "gender")
private Gender personGender;
}
这里也是性别:
public class Gender{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "gender_id")
private int genderId;
@Column(name = "gender_name", unique = true)
private String genderName;
}
创建新的Person时,我已经组装了Thymelef下拉菜单:
@RequestMapping(value = ("/newPerson"), method = RequestMethod.GET)
public ModelAndView createPerson() {
ModelAndView model = new ModelAndView();
Person person= new Person ();
model.addObject("person", person);
List<Gender> genders= genderService.getAll();
model.addObject("genders", genders);
model.setViewName("user/newPerson");
return model;
}
(我意识到它看起来有点愚蠢,但这是我的代码的简化版本。)
这是HTML:
<form class="form-createNew" role="form" method="POST"
th:action="@{/newPerson}" th:object="${person}">
<div class="form-row">
<div class="col">
<div class="form-label-group">
<input type="text" th:field="*{personName}" id="personName" class="form-control" placeholder="Person name">
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<div class="form-label-group">
<select th:field="*{personGender}" class="form-control"
id="personGender" name="personGender">
<option value="" selected disabled hidden>Select gender</option>
<option th:each="gender: ${genders}"
th:value="${gender.genderId}"
th:text="${gender.genderName}"></option>
</select>
</div>
</div>
</div>
<button id="registerBtn" class="btn btn-lg btn-primary btn-block shadow-none text-uppercase" type="submit"> Create </button>
</form>
最后是我的问题:
我在/ newPerson控制器的POST方法中收到的是一个Person对象,其值来自输入字段,但对于Gender为NULL。是什么原因造成的,我在哪里错了?我在SO上也遇到过类似的问题,关于Thymeleaf Docs / Baeldung的问题对我来说也一切正常。
感谢您的帮助! :)
答案 0 :(得分:0)
您正在向您的后置控制器发送如下内容:
personGender:gernderId
您必须这样做:
personGender.genderId:性别ID
为此在您的html中使用:
th:field =“ * {personGender.genderId}”
代替
th:field =“ * {personGender}”
我认为它将为您提供帮助!