在spring mvc issue中创建表单

时间:2014-06-09 12:07:06

标签: java spring spring-mvc

我有两个班级

public class User {
    private int id;     
    priavte List<Hobby> hobbies;
    //setter getter
}

public class Hobby {
    private int id;
    private String hobbyName;
    //setter getter
}

现在我想为User.java创建表单

我的 form.jsp

<form:form method="POST" action="saveEmployee.html" commandName="user" name="register-form" id="register-form" cssClass="smart-green">

<form:select path="hobbies" multiple="true" size="3">
     <form:option value="1">Cricket</form:option>
     <form:option value="2">Computer Games</form:option>
     <form:option value="3">Tennis</form:option>
     <form:option value="4">Music</form:option>
</form:select>
</form:form>

myController.java

@RequestMapping(value = "/saveEmployee.html", method = RequestMethod.POST)
    public ModelAndView addEmployee(
            @ModelAttribute("user") User user BindingResult result) {           
        System.out.println(user.getChoice()); // giving null    
    //   usrDao.saveUser(user);
return new ModelAndView("redirect:add.html", model);
}

我怎样才能从<我的表单获取列表的值,以便我可以获得该值?

1 个答案:

答案 0 :(得分:0)

将多选择值绑定到POJO对象列表的解决方案在CustomCollectionEditor类下完成。这在绑定复杂数据类型时很重要,例如在您的情况下。

在控制器类 myController.java

中添加以下代码
@InitBinder
protected void initBinder(WebDataBinder binder)   
{
   binder.registerCustomEditor(List.class, "hobbies", new CustomCollectionEditor(List.class)
    {
       @Override
       protected Object convertElement(Object element)
        {
           Long id = null;
           String name = null;
           if(element instanceof String && !((String)element).equals(""))  
           {
              //From the JSP 'element' will be a String
              try{
                   id = Long.parseLong((String) element);
                 }
              catch (NumberFormatException e) {
                    e.printStackTrace();
                 }
            }
           else if(element instanceof Long) 
           {
              //From the database 'element' will be a Long
              id = (Long) element;
           }
           // Here you can get Hobby object from database based on the id you have got.
           //You any other way you can get hobbyName and set in hobby object and return it
           Hobby h = new Hobby();
           h.setId(Integer.parseInt(String.valueOf(id)));
           h.setHobbyName(name);
           return h;
     }
  });  
}  

参考链接了解更多详情:
SpringMVC bind Multi Select with object in Form submit
Multiple Select in Spring 3.0 MVC