SpringMVC (7) formatted display, springmvc

Source: Internet
Author: User

SpringMVC (7) formatted display, springmvc

In SpringMVC (6) data verification, we introduced how to verify the correctness of the submitted data. When the data verification is passed, it will be saved. The stored data will be used for future display, which is the value of storage. How can I display the display as required? (For example, a certain number of digits are reserved for decimal places, and the date is in the specified format ). This is what we will talk about in this article-> Format display.

Starting from Spring3.X, Spring provides Converter SPI type conversion and Formatter SPI field parsing/formatting services. Converter SPI implements mutual conversion between objects, formatter SPI converts String to object. Formatter SPI encapsulates Converter SPI and adds support for internationalization. The internal conversion is still completed by Converter SPI.

The following is a simple request and model object conversion process:

Spring provides FormattingConversionService and DefaultFormattingConversionService to parse and format objects. Spring has the following built-in Formatter SPI:

Name Function
NumberFormatter Parses and formats the numbers and strings.
CurrencyFormatter Parses and formats numbers and strings (with currency)
PercentFormatter Parse and format the Number and String (with a percentage)
DateFormatter Parsing and formatting between Date and String
NumberFormatAnnotationFormatterFactory @ NumberFormat annotation to parse and format the Number and String. You can specify a style to indicate the format to be converted (Style. number/Style. currency/Style. percent), of course, you can also specify pattern (such as pattern = "#. # "(retain 2 decimal places), so that the format specified by pattern overwrites the format specified by Style.
JodaDateTimeFormatAnnotationFormatterFactory @ DateTimeFormat annotation for parsing and formatting between the Date type and String. The Date types include Date, Calendar, Long, And Joda. The Joda-Time package must be added to the project.

The following is a demonstration:

First add the Joda-Time package to the previous project, here is the joda-time-2.3.jar, add a formattest. jsp view under the views folder, the content is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    money:<br/>${contentModel.money}<br/>    date:<br/>${contentModel.date}<br/>
    </body>

1. First, we will directly use Formatter for demonstration. Add the FormatModel. java content to the com. demo. web. models package as follows:

package com.demo.web.models;public class FormatModel{        private String money;    private String date;        public String getMoney(){        return money;    }    public String getDate(){        return date;    }        public void setMoney(String money){        this.money=money;    }    public void setDate(String date){        this.date=date;    }        }

Add FormatController. java to the com. demo. web. controllers package as follows:

Package com. demo. web. controllers; import java. math. roundingMode; import java. util. date; import java. util. locale; import org. springframework. context. i18n. localeContextHolder; import org. springframework. format. datetime. dateFormatter; import org. springframework. format. number. currencyFormatter; import org. springframework. stereotype. controller; import org. springframework. ui. model; import org. springframework. web. Bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestMethod; import com. demo. web. models. formatModel; @ Controller @ RequestMapping (value = "/format") public class FormatController {@ RequestMapping (value = "/test", method = {RequestMethod. GET}) public String test (Model model) throws NoSuchFieldException, SecurityException {if (! Model. containsAttribute ("contentModel") {FormatModel formatModel = new FormatModel (); CurrencyFormatter currencyFormatter = new CurrencyFormatter (); currencyFormatter. setFractionDigits (2); // retain 2 decimal places currencyFormatter. setRoundingMode (RoundingMode. HALF_UP); // round to the nearest side. If the distance between the two sides is equal, round up (rounding) DateFormatter dateFormatter = new DateFormatter (); dateFormatter. setPattern ("yyyy-MM-dd HH: mm: ss"); Locale locale = LocaleContextHolder. getLocale (); formatModel. setMoney (currencyFormatter. print (12345.678, locale); formatModel. setDate (dateFormatter. print (new Date (), locale); model. addAttribute ("contentModel", formatModel) ;}return "formattest ";}}

Run the test:

Change the preferred browser language:

Refresh page:

2. In this demonstration, use defaformatformattingconversionservice to change FormatController. java to the following content:

Package com. demo. web. controllers; import java. math. roundingMode; import java. util. date; import org. springframework. format. datetime. dateFormatter; import org. springframework. format. number. currencyFormatter; import org. springframework. format. support. defaultFormattingConversionService; import org. springframework. stereotype. controller; import org. springframework. ui. model; import org. springframework. web. bind. an Notation. requestMapping; import org. springframework. web. bind. annotation. requestMethod; import com. demo. web. models. formatModel; @ Controller @ RequestMapping (value = "/format") public class FormatController {@ RequestMapping (value = "/test", method = {RequestMethod. GET}) public String test (Model model) throws NoSuchFieldException, SecurityException {if (! Model. containsAttribute ("contentModel") {FormatModel formatModel = new FormatModel (); CurrencyFormatter currencyFormatter = new CurrencyFormatter (); currencyFormatter. setFractionDigits (2); // retain 2 decimal places currencyFormatter. setRoundingMode (RoundingMode. HALF_UP); // round to the nearest side. If the distance between the two sides is equal, round up (rounding) DateFormatter dateFormatter = new DateFormatter (); dateFormatter. setPattern ("yyyy-MM-dd HH: mm: ss"); DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService (); conversionService. addFormatter (currencyFormatter); conversionService. addFormatter (dateFormatter); formatModel. setMoney (conversionService. convert (12345.678, String. class); formatModel. setDate (conversionService. convert (new Date (), String. class); model. addAttribute ("contentModel", formatModel) ;}return "formattest ";}}

Locale locale = LocaleContextHolder is missing this time. getLocale (); run the test again, change the language, and refresh it. You can see the same effect as the first method. It means that defaformatformattingconversionservice will automatically return the corresponding format based on the browser request information.

3. Some people may think, ah... I just want to format the display, but it is still so troublesome to write code to convert a field and a field ??? Don't worry. The above is just a demonstration of the built-in formatting converter, which is certainly not used in the actual project. The following describes the annotation-based formatting. First, change FormatModel. java to the following content:

package com.demo.web.models;import java.util.Date;import org.springframework.format.annotation.DateTimeFormat;import org.springframework.format.annotation.NumberFormat;import org.springframework.format.annotation.NumberFormat.Style;public class FormatModel{        @NumberFormat(style=Style.CURRENCY)   private double money;    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")    private Date date;        public double getMoney(){        return money;    }    public Date getDate(){        return date;    }        public void setMoney(double money){        this.money=money;    }    public void setDate(Date date){        this.date=date;    }        }

Note: Here, money and date are no longer of the String type, but their own types.

Change FormatController. java to the following content:

package com.demo.web.controllers;import java.util.Date;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.FormatModel;@Controller@RequestMapping(value = "/format")public class FormatController {        @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model) throws NoSuchFieldException, SecurityException{        if(!model.containsAttribute("contentModel")){                        FormatModel formatModel=new FormatModel();            formatModel.setMoney(12345.678);            formatModel.setDate(new Date());                        model.addAttribute("contentModel", formatModel);        }        return "formattest";    }    }

Note: Only the value assignment in the Code is not formatted.

Modify the formattest. jsp view as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

Note: here you need to add reference <% @ taglib prefix = "spring" uri = "http://www.springframework.org/tags" %> and use spring: eval to bind the value to be displayed.

Run the test to change the browser language, refresh the page, and you can still see the same effect as the first method, proving that the annotation is valid.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.