Spring MVC Getting Started Guide (7): Formatting decimals or dates

When the data is verified, it will be saved by us. The saved data will be used for future presentations, which is the value of saving. So how to display it according to the requirements when it is displayed? (For example: a certain number of digits are reserved for decimals, and the date is in a specified format, etc.). This is what this article is going to talk about -> formatted display.

Starting from Spring 3.X, Spring provides Converter SPI type conversion and Formatter SPI field parsing/formatting services. Converter SPI implements the conversion between objects and objects, and Formatter SPI implements the conversion between String and objects. Formatter SPI is Encapsulates Converter SPI and adds support for internationalization, and its internal conversion is still done by Converter SPI.

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


Spring provides FormattingConversionService and DefaultFormattingConversionService to complete object parsing and formatting. Several Formatter SPIs built into Spring are as follows:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.format.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface NumberFormat {
    NumberFormat.Style style() default NumberFormat.Style.DEFAULT;

    String pattern() default "";

    public static enum Style {
        DEFAULT,
        NUMBER,
        PERCENT,
        CURRENCY;

        private Style() {
        }
    }
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.format.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface DateTimeFormat {
    String style() default "SS";

    DateTimeFormat.ISO iso() default DateTimeFormat.ISO.NONE;

    String pattern() default "";

    public static enum ISO {
        DATE,
        TIME,
        DATE_TIME,
        NONE;

        private ISO() {
        }
    }
}


Let's start the demonstration (formatted decimals or dates) :

First add the Joda-Time package to the previous project, here is joda-time-2.9.9.jar

<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>


Formatting is done here using annotations.

Create entity class: FormatModel.java

package com.ray.models;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

import java.util.Date;

/**
 * @author Ray
 * @date 2018/4/20 0020
 */
public class FormatModel {
    /**
     * Formatting with comments
     */
    @NumberFormat(style = NumberFormat.Style.CURRENCY)
    private double money;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date;

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}


Create the controller FormatController.java

package com.ray.controllers;

import com.ray.models.FormatModel;
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 java.util.Date;

/**
 * @author Ray
 * @date 2018/4/20 0020
 */
@Controller
@RequestMapping(value = "/format")
public class FormatController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(Model model){

        if(!model.containsAttribute("contentModel")){
            FormatModel formatModel = new FormatModel();
            formatModel.setMoney(123456.789);
            formatModel.setDate(new Date());
            model.addAttribute("contentModel",formatModel);
        }
        return "formattest";
    }
}

Create view formattest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Insert title here</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    money:<br/><spring:eval expression="contentModel.money"></spring:eval><br/>
    date:<br/><spring:eval expression="contentModel.date"></spring:eval><br/>
</body>
</html>

Notice:

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


operation result:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393402&siteId=291194637