Monday, September 17, 2007

spring initbinder example that registers custom editor

One of the nice features in Spring is the automatic databinding that occurs if you use one of the subclasses of BaseCommandController such as AbstractCommandController or SimpleFormController. By automatic databinding, I mean Spring initializing your command object based on the request parameters. The magic behind this feature is Spring's builtin property editors which do things like convert strings to integers. Sooner or later, however, you'll run into a situation where you need to do some custom databinding by registering your own PropertyEditor through the initBinder() method.

Suppose this is my command class:


class FootballPlayer {

static enum POSITION {RB, WR, QB, DB, LB}



POSITION _position;



public POSITION getPosition() {

return _position;

}



public void setPosition(POSITION position) {

_position = position;

}

}




So if my request parameter is ?positon=rb and I want my command class to have the correct enum set, do the following:
First, create a custom property editor.

class FootBallPlayerEditor extends PropertyEditorSupport {

public String getAsText() {

FootballPlayer editor = (FootballPlayer) getValue();

return editor.getPosition().name();

}



public void setAsText(final String text) {

setValue(FootballPlayer.POSITION.valueOf(text));

}

}



then override initBinder

protected void initBinder(HttpServletRequest request,

ServletRequestDataBinder binder) {

binder.registerCustomEditor(FootballPlayer.POSITION.class, new FootBallPlayerEditor());

}



And you're all set.

6 comments:

Luis said...

Thanks David... I've been struggling with the 'customPropertyRegistrar' when I stumbled on your blog... You were a big help.

Anonymous said...

Thanks david sir ,

I have a one query plz give me a solution ...

my object coontain list (list contain another object like AcademicInfo) it give error

when i submit my page so plz solve it

org.springframework.beans.InvalidPropertyException:

Anonymous said...

Must editor be of type Position?

Anonymous said...

mussra, check out the registerCustomEditor() method. the first parameter is the type for the editor.

Anonymous said...

i am very new i spring and please give me a simple example to bind multiselect field.

amit said...

how can it will work for date filed