前提:必须在springMVC的配置文件中写上<mvc:annotation-driven></mvc:annotation-driven>
一、@DateTimeFormat 时间格式化
e.g.
前端页面(value值只是为了方便,不用在页面填写):
<form action="/springmvc/testDate" method="post">
<%--<input type="hidden" name="userId" value="1">--%>
username: <input type="text" name="userName" value="kaka">
<br>
age: <input type="text" name="age" value="12">
<br>
birth : <input type="text" name="birth" value="1990-12-12 23:12:24" />
<input type="submit" value="Submit">
</form>
controller 中:
@RequestMapping(value = "/testDate")
public String testDate(User user){
System.out.println(user);
return "success”;
}
实体类 User:
private Integer userId;
private String userName;
private String password;
private int age;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birth;
getters AND setters...
运行:
输出:
二、@NumberFormat 对数字进行格式化
同@DateTimeFormat 在相应的字段上面加上注解
e.g.
@NumberFormat(pattern = "#,###,###.#")
private Float salary;
可以匹配:1,122,111.7