当数据验证通过后就会被我们保存起来。保存的数据会用于以后的展示,这才是保存的价值。那么在展示的时候如何按照要求显示?(比如:小数保留一定的位数,日期按指定的格式等)。这就是本篇要说的内容—>格式化显示。
从Spring3.X开始,Spring提供了Converter SPI类型转换和Formatter SPI字段解析/格式化服务,其中Converter SPI实现对象与对象之间的相互转换,Formatter SPI实现String与对象之间的转换,Formatter SPI是对Converter SPI的封装并添加了对国际化的支持,其内部转换还是由Converter SPI完成。
下面是一个简单的请求与模型对象的转换流程:
Spring提供了FormattingConversionService和DefaultFormattingConversionService来完成对象的解析和格式化。Spring内置的几种Formatter SPI如下:
//
// 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() {
}
}
}
下面就开始演示(格式化显示的小数或者日期):
首先把Joda-Time包添加到之前的项目中,这里用的是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>
这里使用注解的方式进行格式化。
创建实体类: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 {
/**
* 注释方式进行格式化
*/
@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;
}
}
创建控制器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";
}
}
创建视图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>
注意:
这里需要添加引用<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>,并用spring:eval来绑定要显示的值。
运行结果: