java - How to bind String[] to Collection of POJOs? -
i have binder gets string of permissions , must convert collection. when binder method invoking can’t convert array of string collection.
my controller:
@controller @requestmapping("/profile") public class profilecontroller { @autowired @qualifier("mvcuserservice") userservice userservice; @requestmapping(value = "/edit", method = requestmethod.get) public modelandview editform(principal principal) { user user = userservice.getuser(principal.getname()); modelandview mav = new modelandview("user/profile"); return mav.addobject("user", user); } @requestmapping(value = "/edit", method = requestmethod.put) public modelandview edit(@modelattribute("user") user user, bindingresult result) { // action user object } @initbinder public void initbinder(webdatabinder binder) { binder.registercustomeditor(permission.class, new propertyeditorsupport() { @override public void setastext(string name) throws illegalargumentexception { permission permission = userservice.getpermission(name); setvalue(permission); } });
jsp:
<form:form action="/profile/edit" method="put" modelattribute="user"> <input type="hidden" name="_method" value="put"/> // setting fields <form:hidden path="id"/> <form:hidden path="permissions"/> </form:form>
permission class:
public class permission implements serializable { private integer id; private string name;
and user class:
public class user implements serializable { // fields private collection<permission> permissions;
i need implement correct binding. suggestions how can it?
your editor seems lack logic convert csv list list of objects. here code permissionlisteditor convert comma-separated list of strings to/from list collection:
public class permissionlisteditor extends propertyeditorsupport { @override public void setastext(string text) throws illegalargumentexception { list<permission> res = new arraylist(); (string v: text.split(",")) { if (v.trim().length() > 0) res.add(userservice.getpermission(v.trim())); } setvalue(res); } @override public string getastext() { stringbuilder val = new stringbuilder(); (permission p: (list<permission>) getvalue()) { if (val.length() > 0) val.append(", "); val.append(p.getname()); } return val.tostring(); } }
it idea add sort of map lookup permission objects instead of fetching them database one-by one. in constructor:
map<string, permission> map = new hashmap()<>; (permission p: userservice.listpermissions(); map.add(p.getname(), p);
and retrieve objects map in setastext() method:
res.add(map.get(v.trim());
hope helps.
Comments
Post a Comment