java - form creation in spring mvc issue -
i've 2 classes
public class user { private int id; priavte list<hobby> hobbies; //setter getter } public class hobby { private int id; private string hobbyname; //setter getter }
now want create form user.java
my form.jsp is
<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); }
how value list form value?
the solution bind multi select value pojo object list done under customcollectioneditor class. important when binding complex data types such in case.
add below code in controller class 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 jsp 'element' string try{ id = long.parselong((string) element); } catch (numberformatexception e) { e.printstacktrace(); } } else if(element instanceof long) { //from database 'element' long id = (long) element; } // here can hobby object database based on id have got. //you other way can hobbyname , set in hobby object , return hobby h = new hobby(); h.setid(integer.parseint(string.valueof(id))); h.sethobbyname(name); return h; } }); }
reference link more details :
springmvc bind multi select object in form submit
multiple select in spring 3.0 mvc.
Comments
Post a Comment