JSP下拉列表不提交对象

时间:2012-08-01 09:09:16

标签: java spring jsp

我有一个表格,其中填充了数据库中的数据。 之前开始描述我的问题,一些片段:

一堂课:

// @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>

控制器方法进行验证并返回一些错误

@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:无法转换类型的值   [java.lang.String]为属性所需的类型[com.whatever.Area]   'area':找不到匹配的编辑器或转换策略

据我所知,表单只是为'area'提交了纯字符串,而不是从List中绑定对象。

如何让表单提交对象而不是字符串?我的绑定有问题吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

回答我自己的问题,并希望这个家伙获得很多帮助我而不知道的学分;)

我不得不添加一个自定义活页夹......之前从未听说过,所以我先问了很久。

这个链接有关于我发现的那个主题的最好和最短的教程,因为我知道我在寻找什么:  http://empire5.com/development/binding-a-custom-object-in-spring-3/

答案 1 :(得分:0)

我认为对于select你可以尝试这种类型的代码

<select name="area" id="area" >      
  <option value="${areas}">${areas}</option>
</select>