SpringMVC将“把请求参数注入到POJO对象”这个操作称为“数据绑定”。 数据类型的转换和格式化就发生在数据绑定的过程中。 类型转换和格式化是密不可分的两个过程,很多带格式的数据必须明确指定格式之后才可以进行类型转换。 最典型的就是日期类型。
1.使用SpringMVC内置的类型转换器
①配置MVC注解驱动
<mvc:annotation-driven/>
②在需要进行转换的字段上标记特定的注解
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
@NumberFormat(pattern="#,###,###.#")
private double salary;
2.转换失败后处理
①BindingResult
SpringMVC在捕获到类型转换失败错误时会将相关信息封装到BindingResult对象传入到目标handler方法中。
//Return if there were any errors.
boolean hasErrors();
在handler可以通过hasErrors()方法判断是否有错误。如果有则跳转到指定的页面。当然如果有需要也可以获取其他相关信息。
使用BindingResult检测绑定失败错误
@RequestMapping("/convert")
public String convertFail(Employee employee, BindingResult bindingResult) {
//检测是否存在“数据绑定”错误
boolean hasErrors = bindingResult.hasErrors();
if(hasErrors) {
return "error";
}
System.out.println(employee);
return "target";
}
更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120343807
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。