I have a data type in my application called Foo which looks something like this:
public class Foo {
// synthetic primary key
private long id;
// unique business key
private String businessKey;
...
}
This type is used in many forms throughout the web application and typically you want to convert it back and forth using the id
property so I have implemented a Spring3 Formatter that does that and registered that formatter with the global Spring conversion service.
However, I have one form use case where I want to convert using the businessKey
instead. It's easy enough to implement a Formatter to do that, but how do I tell Spring to use that formatter for just this specific form?
I found a document at http://static.springsource.org/spring/previews/ui-format.html which has a section on registering field-specific formatters (see 5.6.6 all the way at the bottom) which offers this example:
@Controller
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerFormatter("myFieldName", new MyCustomFieldFormatter());
}
...
}
This is exactly what I want, but this a preview document from 2009 and it doesn't look like the registerFormatter
method made it into the final released API.
How are you supposed to do this?
Formatters are used to convert String to another Java type and back. So, one type must be String . You cannot, for example, write a formatter that converts a Long to a Date . Examples of formatters are DateFormatter , for parsing String to java. util.
Answer: Front Controller is responsible to handle the entire incoming request of an application. In Spring MVC, dispatcher servlet acts as a front controller and handles the entire incoming requests.
In our application, we use PropertyEditorSupport
class for this. Simple example for handling Calendar, but you can use for any custom class, just override getAsText()
and setAsText()
methods:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
@Override
public void setAsText(String value) {
try {
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(value));
setValue(cal);
} catch (ParseException e) {
setValue(null);
}
}
@Override
public String getAsText() {
if (getValue() == null) {
return "";
}
return new SimpleDateFormat("dd-MM-yyyy").format(((Calendar) getValue()).getTime());
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With