PDA

View Full Version : Spring bind for custom objects


Mahendra Reddy
Apr 3rd, 2006, 10:09 AM
Hi ,

I am using Spring webflow pr5. I face one problem here.I will narate in simple terms I have one screen that display User information. The the bean class is pkg.User.This has one property called role which is of type pkg.Role.Now My screen is bound to form object class pkg.User and I have to display only the role name.So how I should I bind that html control(Text box) to display the role name alone using <spring:bind>.(As this one is my custom datatype for the property which different from Interger,String).

If any example is provided. It is more appriciated.

Thanks

jdwyah
Apr 3rd, 2006, 11:29 AM
Hey there,
If you've got:

class User {
Role role
}
class Role{
String name
}

then you can just bind to the String name like this.
<@spring.formInput "command.user.role.name"/><@spring.showErrors "<br>



If you want to bind right to the Role object, you need to register a custom property editor. Something like:

protected void initBinder(HttpServletRequest arg0, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Role.class, new RoleEditor());
}

public class RoleEditor extends PropertyEditorSupport {

@Override
public String getAsText() {
Role role= (Role)getValue();
if(role== null){
return "";
}
if(role.getRoleId() == null){
return "";
}
return role.getRoleId().toString();
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
try{
Integer id = Integer.parseInt(text);
Role role= new Role(id);
setValue(role);
}catch(NumberFormatException e){
throw new IllegalArgumentException(e);
}
}

}

Mahendra Reddy
Apr 3rd, 2006, 12:39 PM
Hi,

Great Thanks !.. I understood most. But I have one doubt here.. You have used

<@spring.formInput "command.user.role.name"/><@spring.showErrors "<br>

and have bound role.name for display.But in RoleEditor

public String getAsText() {
..
..
return role.getRoleId().toString()
}

Here, Why do we return 'roleId' instead of 'roleName' ?


Thanks !

jdwyah
Apr 3rd, 2006, 02:49 PM
I was giving you two different things to try. If Role has a String name member then you don't need the Custom prop editor at all.



The other example is if Role isn't something with nice String, Integer members but some other object in your domain.