spring 3.2 mvc如何接收复杂对象?
在下面的简单示例中,我有两个模型类,具有多对一的关系。添加新的 Employee 对象时,我想使用 html 选择来选择它的部门。
当我发布添加新员工时,我收到以下错误:
无法将 java.lang.String 类型的属性值转换为属性部门所需的 hu.pikk.model.Department 类型;嵌套异常是 java.lang.IllegalStateException:无法将类型 [java.lang.String] 的值转换为属性部门所需的类型 [hu.pikk.model.Department]:找不到匹配的编辑器或转换策略
我应该如何实施编辑器或转换策略?是否有值得关注的最佳实践或陷阱?
我已经阅读了 spring mvc 文档,以及一些文章和 stackoverflow 问题,但老实说,我发现它们有点令人困惑,而且很多时候太短,太随意了。
楷模:
@Entity
public class Employee {
@Id
@GeneratedValue
private int employeeId;
@NotEmpty
private String name;
@ManyToOne
@JoinColumn(name="department_id")
private Department department;
//getters,setters
}
@Entity
public class Department {
@Id
@GeneratedValue
private int departmentId;
@Column
private String departmentName;
@OneToMany
@JoinColumn(name = "department_id")
private List<Employee> employees;
//getters,setters
}
在我的控制器类中:
@RequestMapping(value = "/add", method = RequestMethod.GET)
private String addNew(ModelMap model) {
Employee newEmployee = new Employee();
model.addAttribute("employee", newEmployee);
model.addAttribute("departments", departmentDao.getAllDepartments());
return "employee/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
private String addNewHandle(@Valid Employee employee, BindingResult bindingResult, ModelMap model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute("departments", departmentDao.getAllDepartments());
return "employee/add";
}
employeeDao.persist(employee);
redirectAttributes.addFlashAttribute("added_employee", employee.getName());
redirectAttributes.addFlashAttribute("message", "employee added...");
return "redirect:list";
}
在 add.jsp 中:
<f:form commandName="employee" action="${pageContext.request.contextPath}/employee/add" method="POST">
<table>
<tr>
<td><f:label path="name">Name:</f:label></td>
<td><f:input path="name" /></td>
<td><f:errors path="name" class="error" /></td>
</tr>
<tr>
<td><f:label path="department">Department:</f:label></td>
<td><f:select path="department">
<f:option value="${null}" label="NO DEPARTMENT" />
<f:options items="${departments}" itemLabel="departmentName" itemValue="departmentId" />
</f:select></td>
<td><f:errors path="department" class="error" /></td>
</tr>
</table>
<input type="submit" value="Add Employee">
</f:form>