首页 > 编程语言 > 详细

spring mvc 日期类型转换问题 @initBinder解决前台与后台的日期格式不统一问题

时间:2019-10-23 17:57:08      阅读:82      评论:0      收藏:0      [点我收藏+]

在用ssm框架开发web程序的时候发现后台传到前台的日期可能格式不是我们想要的
可以用以下解决方案
1.在controller里面添加一个方法

/**
* 加入以下方法 解决spring无法转换date数据的问题
* @param request
* @param binder
*/
@InitBinder
public void InitBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
// 不要删除下行注释!!! 将来"yyyy-MM-dd"将配置到properties文件中
// SimpleDateFormat dateFormat = new
// SimpleDateFormat(getText("date.format", request.getLocale()));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null, new CustomDateEditor(
dateFormat, true));
}

这里如果项目中经常涉及这种格式转换,可以将这个方法放在baseController里面,用继承就可以了,避免每一个controller里面都要去写一个这个方法。

2.使用JsonFormat注解放到实体日期属性上

@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")



spring mvc 日期类型转换问题 @initBinder解决前台与后台的日期格式不统一问题

原文:https://www.cnblogs.com/guanxiaohe/p/11727524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!