Bean parameter conversion
Spring MVC provides ConversionService
to convert data to bean target type from from data.
In MVC, we can use custom ParamConverter
to convert form data to the target type.
Parameter conversion
As an example, add a dueDate
to Task
entity. We need to convert the form field value(it is a String
) to LocalDate
type.
Create a custom
ParamConverterProvider
forLocalDate
.Add a new field dueDate to
TaskForm
, which type isLocalDate
.In the view, add a new form field named
duedate
.
When the form is submitted, the duedate
will be converted to LocalDate
type and bind to dueDate
property of TaskForm
.
Format
Spring provides Formatting service in the display view. eg. @DateFormat
and custom Formatters.
Unfortunately, MVC does not support such features. And JSTL fmt:formatDate
does not accept Java 8 DateTime APIs.
We can define a custom CDI beans for date formatting, and call it via expression language.
Create
RequestScoped
beanFormatters
.Apply it on the
dueDate
in the details.jspx page.
The result looks like:
Source Codes
Clone the codes from my GitHub account.
Open the mvc project in NetBeans IDE.
Run it on Glassfish.
After it is deployed and running on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.
Last updated