@NumberFormat
注解的作用
负责输入输出数据的格式化工作,如将数据转换成特定的货币类型格式,百分比类型格式等
pattern
:类型String
,使用自定义的数字格式化串,如##,###
表示50,000
style
:类型NumberFormat.Style
,几个常用值Style.CURRENCY
:货币类型Style.NUMBER
:正常数字类型Style.PERCENT
:百分比类型
使用示例
先写个 index.html
,分别测试整数、百分数、货币类型
<!DOCTYPE html>
<html>
<head>
<title>Spring MVC的数据类型转换</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="resources/jquery-3.1.0.js"></script>
<script type="text/javascript" src="resources/json2.js"></script>
</head>
<body>
<form action="register" method="post">
整数类型:<input type="text" name="total" /> <br><br>
百分数类型:<input type="text" name="discount" /><br><br>
货币类型:<input type="text" name="money" /><br><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
实体类 User
,注解就加在该类的实例变量上
public class User {
@NumberFormat(style=Style.NUMBER,pattern="#,###")
private int total;
@NumberFormat(style=Style.PERCENT)
private double discount;
@NumberFormat(style=Style.CURRENCY)
private double money;
}
controller
层
@Controller
public class UserController {
@RequestMapping("/register")
public String register(User user,Model model){
model.addAttribute("user", user);
return "result";
}
}
result.jsp
页面
<%@page pageEncoding="utf-8"
contentType="text/html;charset=utf-8" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试AnnotationFormatterFactory</title>
</head>
<body>
<h3>测试表单数据格式化</h3>
<form:form modelAttribute="user" method="post" action="" >
<table>
<tr>
<td>整数类型:</td>
<td><form:input path="total"/></td>
</tr>
<tr>
<td>百分数类型:</td>
<td><form:input path="discount"/></td>
</tr>
<tr>
<td>货币类型:</td>
<td><form:input path="money"/></td>
</tr>
</table>
</form:form>
</body>
</html>
输入
输出