Registering PropertyEditors’s with spring for custom objects

More often than not people come to the spring forums asking about PropertyEditor’s. 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 user’s 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.

Let’s say you have a list of user’s 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" />
</form:form>

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;

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		Integer userId = new Integer(text);
		super.setValue(userService.getUser(userId));
	}
}

Thats it. Your property editor is now implemented. You will no longer recieve 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.

@InitBinder
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, i’d 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.

Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark

No related posts.

Tags: , ,

2 Responses to “Registering PropertyEditors’s with spring for custom objects”

  1. yarco says:

    thanks, this REALLY helped out!

  2. Milan Scekic says:

    Thank you, you REALLY help me and save a lot of time!

Leave a Reply