【发布时间】:2013-11-13 15:29:21
【问题描述】:
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>
【问题讨论】:
-
你应该做的是显示
Department名称的下拉列表,但只发布部门的ID。然后,您可以检索Department并将其设置为新的Employee。 -
@SotiriosDelimanolis 如果我没记错的话,这就是我在 jsp 中一直在做的事情。问题是,当控制器收到 POST 时,它不知道如何将 id 字符串转换为 Department 对象。如果我理解正确,我必须为此实现并注册一个 Converter
。我想知道这方面是否有最佳实践。比如这个东西怎么打包,哪个更好,editor还是converter,是不是应该在Converter里面查询数据库,还是有更好的办法?等等…… -
它正在尝试将 id 转换为
Department,因为请求参数名称是department。如果你将它(不要使用form标签库)更改为<input name="departmentId">并为其添加@RequestParam,则可以从某个DAO层查询Department对象并调用EmployeeDepartment的设置器。我认为在这里执行此操作比在任何Converter中执行此操作要好。
标签: java spring-mvc data-binding