springmvc中的格式化主要包括日期格式化和数字格式化。我们这一节将阐述springmvc中的格式化。
1、环境约束
- win10 64位操作系统
- idea2018.1.5
- jdk-8u162-windows-x64
- spring4.2.4
2、前提约束
- 完成基于注解的springmvc的demo https://www.jianshu.com/p/d1a84f07c98f
3、操作步骤
- 在src文件夹下创建net.wanho.controller.FormatController.java,内容如下:
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
@Controller
public class FormatController{
@RequestMapping("/format")
@ResponseBody
public String testFormat(User user)
{
return user.toString();
}
}
class User{
private int id;
private String name;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday; //提供get/set方法
@NumberFormat(pattern="#,###,###.#")
private Float salary; //提供get/set方法
public User() {
}
public User(int id, String name, Date birthday, Float salary) {
this.id = id;
this.name = name;
this.birthday = birthday;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", birthday=" + birthday +
", salary=" + salary +
'}';
}
}
- 启动tomcat,在浏览器中输入 http://localhost:8080/format?salary=1,234,456.4&birthday=2011-11-11
以上就是springmvc中数据的格式化。