
正文
springmvc之格式化要显示的小数或者日期。
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
把保存的小数或者日期按照想要的格式显示。
首先导入jar包joda-time-2.3.jar,下载地址http://pan.baidu.com/s/1gfNuUfp
这里使用注解的方式进行格式化。
创建实体类:FormatModel.java
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 void setMoney(double money) {
this.money = money;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
创建控制器FormatController.java
@Controller
@RequestMapping("/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"%>
<!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" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</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来绑定要显示的值。
运行http://localhost:8080/项目名称/format/test
运行结果:
money:
¥123,456.79
date:
2017-01-04 16:55:37








