Custom Editors and Formatters
Learn how custom formatters can be used to directly bind to richer objects.
We'll cover the following...
With Spring MVC and Thymeleaf, we have to convert Java objects from the HTML <input>
values. Using String on the FormData
objects makes this process trivial.
However, there might be cases where we want to bind to a richer object directly. This can be done by implementing a custom property editor or a custom formatter.
Custom editor
We’ll use PhoneNumber
as an example. In AbstractUserFormData
, we currently have this:
@NotBlank@Pattern(regexp = "[0-9.\\-() x/+]+", groups = ValidationGroupOne.class)private String phoneNumber;
If we want to use the PhoneNumber
class instead of String
, we’ll need to create a custom property editor:
package com.tamingthymeleaf.application.user;import org.apache.commons.lang3.StringUtils;import java.beans.PropertyEditorSupport;public class PhoneNumberPropertyEditor extends PropertyEditorSupport {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (StringUtils.isNotBlank(text)) {this.setValue(new PhoneNumber(text));} else {this.setValue(null);}}@Overridepublic String getAsText() {PhoneNumber value = (PhoneNumber) getValue();return value != null ? value.asString() : "";}}
-
Extend from PropertyEditorSupport (Which is a Java SDK class, not a Spring class).
-
Override the
setAsText(String text)
method. This method must implement the conversion fromString
to the custom type (PhoneNumber
in our example). -
If the text is not blank, create a
PhoneNumber
...