I am trying to get a custom formatter working in Spring MVC. I've looked at several posts regarding this, including: Custom Annotation-driven Formatting Spring MVC. I have traced through my application and I know that the formatter is being registered. Since I am confident that the formatter is registered I think its the annotation that is being ignored, but I dont know why.
For reference here is how I register the formatter factory:
@Override
public void addFormatters(FormatterRegistry registry)
{
registry.addFormatterForFieldAnnotation(new PhoneNumberFormatAnnotationFormatterFactory());
}
Annotation:
@Target(value = { ElementType.FIELD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface PhoneNumber
{
}
Formatter Factory:
public class PhoneNumberFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<PhoneNumber>
{
@Override
public Set<Class<?>> getFieldTypes()
{
Set<Class<?>> setTypes = new HashSet<Class<?>>();
// setTypes.add(String.class);
setTypes.add(PhoneNumber.class);
return setTypes;
}
@Override
public Printer<?> getPrinter(PhoneNumber annotation, Class<?> fieldType)
{
return new PhoneNumberFormatter();
}
@Override
public Parser<?> getParser(PhoneNumber annotation, Class<?> fieldType)
{
return new PhoneNumberFormatter();
}
}
Formatter:
public class PhoneNumberFormatter implements Formatter<String>
{
private static final Logger logger = Logger.getLogger(PhoneNumberFormatter.class);
@Override
public String print(String subject, Locale locale)
{
logger.debug("formatting phone number");
return subject + "BOO";
}
@Override
public String parse(String text, Locale locale) throws ParseException
{
return text;
}
}
Usage in the view:
<tr>
<td>Phone:</td>
<td>${workOrderDetailBean.subscriberPhone}</td>
</tr>
2 things you need to do:
String.class
instead of PhoneNumber.class
(assuming your bean is storing the phone number as a String
)<spring:eval expression="workOrderDetailBean.subscriberPhone" htmlEscape="false"/>