JSF 2.0 – converting objects without a Converter

29 September 2012, 6:01 pm

As is so often the case, the best solution is also the simplest. I’ve been developing a personal web app, using JSF 2.0 for the presentation layer. I’m used to creating custom Converters using the @FacesConverter annotation to carry out the conversion from String to Object format and vice versa. This is useful when the String representation and the Object are loosely coupled. For some reason this particular converter was proving problematic. It wasn’t until I happened to implement a toString() method on the object that I realised, in many cases this is all you need: http://docs.oracle.com/javaee/6/api/javax/faces/component/UIOutput.html (for an explanation)

So many Java libraries make use of the basic object methods (toString, equals and hashCode), and so those wiser Java lecturers and developers weren’t lying to you when they said make sure you always implement them!

One Comment

I should add – in this circumstance the field that the chosen value of these radio buttons is bound to in the backing bean is of type String – So the toString() value ends up here. If you want the field to be populated with the data object chosen from your collection, or a non-string value, you will either need a converter or you can also use the simpler:

Personally I prefer reducing the use of converters where possible, if you’re not careful you can end up filing them with far more logic than is wise.