springMVC 中日期问题相关

本文介绍如何解决SpringMVC中从String类型转换到Date类型的问题,并演示如何使用@InitBinder注解和WebDataBinder实现自定义类型转换。此外,还提供了处理JSON中日期格式的方法,确保从前端接收到正确的日期格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring mvc 中的类型转换问题

若是前台传来controller的是String类型,可是需要的是Date类型,会产生如下错误:

Field error in object 'perform' on field 'startTime': rejected value [2018-06-29 16:08:00]; codes [typeMismatch.perform.startTime,typeMismatch.startTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [perform.startTime,startTime]; arguments []; default message [startTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2018-06-29 16:08:00'; nested exception is java.lang.IllegalArgumentException]

此时需要自定义数据的绑定,绑定方法,将字符串转换为日期队形。

需要使用springmvc的@InitBinder注解,还有spring自带的WebDataBinder。WebDataBinder使用来绑定请求参数到指定的属性编辑器的。当前台传来的参数是string类型时,当往model里面进行set的时候,如果他set的属性是个对象,spring就会找对应的便捷器进行转换,然后在进行set.

代码如下:

@InitBinder
	public void initBinder(WebDataBinder binder)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
对Json中日期的处理

将数据库中的信息取出来后,放到集合list后,再将list转为jsonobject发送到前台。

Long total = performService.count(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(performList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);

可是前台一直显示的日期是[object,object],看一下传向前台的json数组即可知道原因。

"endTime":{"date":1,"day":5,"hours":18,"minutes":18,"month":5,"seconds":4,"time":1527848284000,"timezoneOffset":-480,"year":118},

所以要对这个json进行处理,使他能显示出我想要的格式。本来想的是在前台用js处理,但是试了一下发现,不仅需要写的代码量比较大(要进行分割字符创等操作),而且所得到的格式也不尽如人意,所以我们要在后台进行处理。处理方法也比较简单。

 Long total = performService.count(map);
		JSONObject result = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm"));
		JSONArray jsonArray = JSONArray.fromObject(performList,jsonConfig);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);

在debug一次可以发现,json的内容已经进行了改变。

"endTime":"2018-06-01 18:18"

此时前台也能看到想要的数据格式了。

在jsp中日期的处理
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:formatDate value="${film.publishDate}" pattern="yyyy-MM-dd"  type="date" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值