我有一个表单,其中填充了来自数据库的数据。 在开始描述我的问题之前,先看一些片段:
一类:
// @Entity for areas
public class Area {
@Id
@Column(name = "area")
private String area;
@Column(name = "deleted")
private boolean deleted;
getter/setter
}
二等舱
// @Entity for employees
public class Employee {
@Id
@GeneratedValue
@Column(name = "ID")
private long id;
@ManyToOne
@JoinColumn(name = "area")
private Area area;
@Column(name = "name")
private String name;
getter/setter
调用EmployeeController中的方法返回数据给jsp
protected String createDialog( @PathVariable("id") Long id, Model model ){
Employee employee = id == 0 ? new Employee() : employeeService.findById(id);
//return employee
model.addAttribute("employeeModel", employee );
//add data needed to create dropdown holding areas
//areaService.findAll returns a List<Area>
model.addAttribute("areas", areaService.findAll(
new Sort(
Sort.Direction.ASC,
"area"
)
));
return "employees/dialogUpdateEdit";
}
jsp,显示区域的下拉列表,如果没有返回新员工,则显示已知数据
<form:form action="employees/ajax" commandName="employeeModel" method="POST" id="createForm">
<table class="fullWidth">
<tr>
<td>Area</td>
<td>
<form:select path="area" items="${areas}" class="fullWidth">
</form:select>
</td>
</tr>
<tr>
<td>Employee Name</td>
<td><form:input path="name" class="fullWidth"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" id="btnSaveEmployee" class="fullWidth" />
</td>
</tr>
</table>
<!-- adding hidden field to hold id on update -->
<form:hidden path="id" />
</form:form>
Controller 方法进行验证并返回或不返回一些错误
@RequestMapping(value = "/ajax", method = RequestMethod.POST)
protected @ResponseBody ValidationResponse createOrUpdate(
@Validated @ModelAttribute("employeeModel") Employee employee,
BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
employeeService.createOrUpdate(employee);
}
return validate(employee, null, bindingResult);
}
对于问题: 这一切都很好,下拉列表被填充,数据被填充到输入中。 但是当我点击提交时,出现以下错误:
java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.whatever.Area] for property 'area': no matching editors or conversion strategy found
据我所知,表单只是提交“区域”的纯字符串,而不是绑定(bind)列表中的对象。
如何让表单提交对象而不是字符串?我的绑定(bind)有问题吗?
感谢您的帮助!
最佳答案
回答我自己的问题,并希望那个在不知情的情况下帮助我的人得到很多学分;)
我不得不添加一个自定义 Binder ...以前从未听说过,所以我先问了很长的路要走。
自从我知道自己在寻找什么以来,此链接包含关于该主题的最好和最短的教程: http://empire5.com/development/binding-a-custom-object-in-spring-3/
关于java - JSP下拉不提交对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11756051/