跳至主要内容

Getting started with Java EE 8 MVC(8)-Parameter conversion

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.
  1. Create a custom ParamConverterProvider for LocalDate.
    @Provider
    public class CustomConverterProvider implements ParamConverterProvider {
    
        final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ISO_DATE;
    
        @Override
        public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
    
            if (rawType.getName().equals(LocalDate.class.getName())) {
    
                return new ParamConverter<T>() {
                    @Override
                    public T fromString(String value) {
                        return value != null ? (T) LocalDate.parse(value, DATE_FORMAT) : null;
                    }
    
                    @Override
                    public String toString(T value) {
                        return value != null ? ((LocalDate) value).format(DATE_FORMAT) : "";
                    }
                };
            } 
            ....
    }
    
  2. Add a new field dueDate to TaskForm, which type is LocalDate.
    @NotNull
    @FormParam("duedate")
    private LocalDate dueDate;
    
  3. In the view, add a new form field named duedate.
    <input type="text" id="duedate" name="duedate" class="form-control" placeholder="Due date"/>
    
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.
  1. Create RequestScoped bean Formatters.
    @RequestScoped
    @Named("formatters")
    public class Formatters {
    
        static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_DATE;
    
        public String formatDate(LocalDate data) {
            return DATE_FORMATTER.format(data);
        }
    
    }
    
  2. Apply it on the dueDate in the details.jspx page.
    <dt>Due date:</dt>
    <dd>${formatters.formatDate(details.dueDate)}</dd>
    
The result looks like:
date formatting result

Source Codes

  1. Clone the codes from my github.com account.
    https://github.com/hantsy/ee8-sandbox/
  2. Open the mvc project in NetBeans IDE.
  3. Run it on Glassfish.
  4. After it is deployed and runging on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.
发表评论

此博客中的热门博文

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse thePostentity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute converter In this example…

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to addhibernate-enversas project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…