I’m new to Spring and trying to use the Spring Formatting SPI for UI layer parsing and printing of values.
I’ve defined a custom formatter and have the parsing side working correctly and if I do a direct conversionService.convert(someObject, String.class) call then the value is converted (i.e. print()ed) correctly using the formatter I’ve defined.
However, in my template I’m only getting the object’s toString() representation displayed rather than the String from the registered conversionService.convert() call.
I’m using Mustache as the templating engine instead of Velocity or Freemarker (thank God). Is the Formatting SPI tied to JSP tags and/or do I need to extend the Mustache library I’m using to support Spring bind/form tags in order for this to work correctly?
I’ve scoured the documentation and searched all over and cannot find any information on this, but my apologies if my RTFM/Google skills are lacking.
First of all, if you look at the pom.xml file for that Mustache Spring View library, it’s not using Mustache.java, it’s actually using Jmustache:
https://github.com/sps/mustache-spring-view/blob/master/pom.xml
You can find Jmustache here:
https://github.com/samskivert/jmustache
The view just passes your model as a Map<String, Object> to the Jmustache Template “execute()” method, so Spring is not involved anymore after that point. At that point it’s all about Jmustache figuring out how to generate output using your template syntax and your model values. The Jmustache code is a bit convoluted and hard to follow, but I think if you look at the “Template.Segment” subclasses defined in the Mustache class you will see where the Object values are getting turned to Strings using String.valueOf(Object) on line 568:
https://github.com/samskivert/jmustache/blob/master/src/main/java/com/samskivert/mustache/Mustache.java
String.valueOf(Object) just calls toString() on the Object passed in (if it’s not null):
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29
I think you’ve got two options. Handle all the String conversions yourself in your controller, before populating your model, and then make sure to populate your model only with String values. Or, you can try to extend or modify the Jmustache code to have it use Spring’s conversion API to handle the conversions to strings instead of using String.valueOf().