特殊数据处理
需要结合封装类
数据格式化
时间:
org.springframework.format.annotation.DateTimeFormat
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
//转换后可以获取页面传递的字符串时间(从页面到方法)
//从方法到页面:页面是不能直接获取date类型,页面需要对date类型做格式化
精度:
org.springframework.format.annotation.NumberFormat
@NumberFormat(pattern="#,###,###.#")
private Double salary;//正常接受价格精度。
用字符串可以解决这些麻烦的转换
注意:这里不需要扫描DTO包,但是核心配置必须使用下面注解:
<mvc:annotation-driven></mvc:annotation-driven>
这个注解的功能大于单独的注解处理器和适配器的能力。
页面:
时间:
<fmt:formatDate value="{user.birth}" pattern="yyyy-MM-dd"/> 显示可选精度:
Dto中加入 Date 类型 并加入注解。
在请求中使用 SimpleDateFormat进行处理。
测试输出:
从方法到页面, 这里面我们可以通过jstl 里面的 fmt标签进行时间的处理。
后端代码:
@RequestMapping("six.do")
public String goToSix(Model model){
Dto dto =new Dto("张颖豪","123",new String[]{"爱啦啦啦","aixxxx是"},new Date());
model.addAttribute("six",dto);
return "/index.jsp";
}
前端代码:
<html>
<body>
<h2>Hello World!</h2>
{six.username}
{six.password}
<c:forEach items="{six.like}" var="item">{item}
</c:forEach>
<fmt:formatDate value="${six.birth}" pattern="yyyy/MM/dd/hh:mm:ss"></fmt:formatDate>
</body>
</html>
运行结果:
精度测试: 依照实际情况自己进行配置
在Dto 中: 注意注解
@NumberFormat(pattern = "#,###,###.#")
private Double price;
后端代码中,传入一个小数点很长的数值
在前端 jsp 界面解析的时候 :
<fmt:formatNumber value="${six.price}" pattern="#,###,###.#" maxFractionDigits="2" minFractionDigits="2"></fmt:formatNumber>
maxFractionDigits :最大小数点长度
minFractionDigits : 最小小数点长度
结果如下: 注意小数点长度 为两位 并且 数值四舍五入
嵌套绑定数据(了解)
使用JavaBean绑定数据的时候需要注意,页面上控件的名称和DTO中的属性名称一致。
注意:DTO获取某个字段失败,跳转Action会失败。
注意页面属性名称有嵌套
如:
增加的用户名:<input type="text" name="other.username">
增加的密码:<input type="password" name="other.password">
在five.do文件里面做处理:
演示:
上面箭头指向为嵌套对象 , 并且嵌套字段里面有两个属性值。
正确获取到嵌套对象里面的属性值。