Want create site? Find Free WordPress Themes and plugins.

More often than not people come to the spring forums asking about PropertyEditors. PropertyEditors are needed when you want to convert a string value to an object. Say for example, your command object contains a reference to a User object and the list of users is shown in the jsp with the value of the option box serving as the id of the user. Once the form is submitted, unless you have a custom property editor for your user class, you will receive validation errors.

Lets say you have a list of users out of whom one of them needs to be selected. Your User class looks something like this :

public class User {
private int    userId;
private String userName;

//..getters and setters..
The command object:

public class SelectUserForm {

private User user;

The jsp :

<form:form method="POST" commandName="selectUserForm">
User : <form:select path="city" items="${userList}" itemValue="userId" itemLabel="userName" />

The userList is put into the model by the controller.

For spring to bind the data submitted to a user object, it needs to know of a property editor which allows it to do so.

The property editor:

public class UserPropertyEditor extends PropertyEditorSupport {

private Log    log     = LogFactory.getLog(getClass());
private UserService userService;

public void setAsText(String text) throws IllegalArgumentException {
Integer userId = new Integer(text);

Thats it. Your property editor is now implemented. You will no longer receive validation errors when you bind a user object.

Remember that the editor also needs to be registered in your controller for spring to use it while converting to the object.

protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(User.class, new UserPropertyEditor());
super.initBinder(request, binder);

The annotation is only neccessary if you’re using annotation based controller. That’s it, you’re good to go.

Before you go ahead and implement your own property editor, id strongly suggest going through the list of built-in spring property editors and see if one of them suits your needs, reinventing the wheel doesn’t help anybody.

Did you find apk for android? You can find new Free Android Games and apps.

Leave A Reply