4

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>
4

2 回答 2

3

问题是,当控制器收到 POST 时,它不知道如何将 id 字符串转换为 Department 对象。我发现基本上有三种方法可以解决这个问题:

  1. 不使用spring form jstl,而是使用自定义名称的简单html选择,并在Controller中使用@RequestParam读取它,访问数据库并填充它。
  2. 实现 Converter 接口,并将其注册为 bean。
  3. 实现 PropertyEditor 接口。通过扩展 PropertyEditorSupport 类更容易做到这一点。

我选择了第三种选择。(稍后当我有时间时,我将使用前两个选项来编辑这个答案。)

2.实现Converter<String, Department>接口

@Component 
public class DepartmentConverter implements Converter<String,Department>{
    @Autowired
    private DepartmentDao departmentDao;
    @Override
    public Department convert(String id){
        Department department = null;
        try {
            Integer id = Integer.parseInt(text);
            department = departmentDao.getById(id);
            System.out.println("Department name:" + department.getDepartmentName());
        } catch (NumberFormatException ex) {
            System.out.println("Department will be null");
        }
        return department;
    }
}

在 spring bean 配置文件中:

<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
  class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="package.DepartmentConverter"/>
        </list>
    </property>
</bean>

3. 扩展 PropertyEditorSupport 类

public class SimpleDepartmentEditor extends PropertyEditorSupport {

    private DepartmentDao departmentDao;

    public SimpleDepartmentEditor(DepartmentDao departmentDao){
        this.departmentDao = departmentDao;
    }
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Department department = null;
        try {
            Integer id = Integer.parseInt(text);
            department = departmentDao.getById(id);
            System.out.println("Department name:" + department.getDepartmentName());
        } catch (NumberFormatException ex) {
            System.out.println("Department will be null");
        }
        setValue(department);
    }
}

在 Controller 内部,我需要添加一个 @InitBinder:

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Department.class, new SimpleDepartmentEditor(departmentDao));
    }
于 2013-11-19T01:02:32.310 回答
0

我认为你在这里遇到了下一个情况。当 Spring 试图反序列化Employee在其中接收到的实体时,addNewHandle它找到department了 String 类型的属性,但在目标实体中它具有Department类型,那么,因为您没有针对此类转换的转换 regsieterd,它会失败。因此,为了解决这个问题,您可以实现自己的转换器 ( Converter ),它获取 String 并返回Department并注册它,conversionService或者您可以通过覆盖Jackson JsonDeserializerdepartment@JsonDeserialize(using=<your Jacson custom deserializer>.class). 希望这可以帮助。

于 2013-11-13T16:21:04.003 回答