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

在用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")



猜你喜欢

转载自www.cnblogs.com/guanxiaohe/p/11727524.html