Close

Spring MVC - Creating a new Formatter

[Last Updated: Nov 19, 2016]

In this example we are going to define our own formatter using spring Formatter SPI. Spring Formatter interface extends Printer and Parser interfaces:

 package org.springframework.format;
 public interface Formatter<T> extends Printer<T>, Parser<T> {
 }

We have to implement print() and parse() methods of Printer and Parser respectively.



we are going to demonstrate how to format an object of Address instance in Customer object.

Creating Backing object classes

public class Customer {
    private Long id;
    private String name;
    private Address address;

   //getters and setters
}

public class Address {
    private String street;
    private String city;
    private String county;
    private String zipCode;

    //getters and setters
}



Creating our Formatter

import org.springframework.format.Formatter;
import java.text.ParseException;
import java.util.Locale;

public class AddressFormatter implements Formatter<Address> {
    private Style style = Style.FULL;

    public void setStyle (Style style) {
        this.style = style;
    }

    @Override
    public Address parse (String text, Locale locale) throws ParseException {
        if (text != null) {
            String[] parts = text.split(",");
            if (style == Style.FULL && parts.length == 4) {
                Address address = new Address();
                address.setStreet(parts[0].trim());
                address.setCity(parts[1].trim());
                address.setZipCode(parts[2].trim());
                address.setCounty(parts[3].trim());
                return address;
            } else if (style == Style.REGION && parts.length == 3) {
                Address address = new Address();
                address.setCity(parts[0].trim());
                address.setZipCode(parts[1].trim());
                address.setCounty(parts[4].trim());
                return address;
            }
        }
        return null;
    }

    @Override
    public String print (Address a, Locale l) {
        if (a == null) {
            return "";
        }
        switch (style) {
            case FULL:
                return String.format(l, "%s, %s, %s, %s", a.getStreet(), a.getCity(),
                                     a.getZipCode(), a.getCounty());
            case REGION:
                return String.format(l, "%s, %s, %s", a.getCity(), a.getZipCode(),
                                     a.getCounty());
        }
        return a.toString();
    }

    public enum Style {
        FULL,
        REGION
    }
}



Registering The Formatter

import org.springframework.context.annotation.Configuration;
 import org.springframework.format.FormatterRegistry;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

 @EnableWebMvc
 @Configuration
 public class MyWebConfig extends WebMvcConfigurerAdapter {

     @Override
   public void addFormatters (FormatterRegistry registry) {
   AddressFormatter addressFormatter = new AddressFormatter();
   addressFormatter.setStyle(AddressFormatter.Style.REGION);
   registry.addFormatter(addressFormatter);
   }
 }

Alternatively we could have used @InitBinder approach, if we want to customize AddressFormatter per request basis.




Creating Controller

@Controller
@RequestMapping("/customers")
public class CustomerController {
    @Autowired
    private CustomerDataService customerDataService;

    @RequestMapping(method = RequestMethod.GET)
    private String handleRequest (Model model) {
        model.addAttribute("customerList", customerDataService.getAllUsers());
        return "customers";
    }
}




customer.jsp

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
<body>
<h3>Customer List </h3>
<table style="width:100%">
<c:forEach var="customer" items="${customerList}" varStatus="status">
<tr>
<td>
    <spring:eval expression="customer.id" />
</td>
<td>
    <spring:eval expression="customer.name" />
</td>
<td>
   <spring:eval expression="customer.address" />
</td>
</tr>
</c:forEach>
</table>
</body>
</html>


Example Project

Run the web application by using embedded tomcat:

mvn  clean install tomcat7:run-war

Dependencies and Technologies Used:

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • javax.servlet:jstl 1.2
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • DataFactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.0.4

Spring Custom Formatter Select All Download
  • spring-custom-formatter
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AddressFormatter.java
          • webapp
            • WEB-INF
              • views
        • test
          • java
            • com
              • logicbig
                • example

    See Also