I would like to know how to use Converters in Java Server Faces similar to Spring collection property editor
Suppose the following model
public class Group {
private String name;
List<User> users = new ArrayList<User>();
// getter's and setter's
}
And equivalent form
<form ...>
<h1>Group form</h1>
<label for="name">Enter name</label>
<input type="text" name="name"/>
<label for="users">Select users</label>
<!--value attribute stores userId-->
<input type="checkbox" value="1" name="users"/> User 1
<input type="checkbox" value="2" name="users"/> User 2
<input type="checkbox" value="3" name="users"/> User 3
</form>
If i use Spring to bind users property in Group class, i call
binder.registerCustomEditor(List.class, new CustomCollectionEditor() {
protected Object convertElement(Object userId) {
return new User((Integer) userId);
}
});
How do i get the same effect when using Java Server Faces ?
regards,
For that you can implement
javax.faces.convert.Converter. Its API is pretty self-explaining: write thegetAsString()method accordingly that it returns theStringrepresentation of theObject, which can be under each the technical ID such asuserId. Then, to get JSF set the rightObjectduring apply request parameters phase, you need to implementgetAsObject()that it returns theObjectassociated with the givenStringvalue.Basically:
Register it in
faces-config.xmlas follows:That should be it. For more insights you may this or this article useful.