springMVC 中日期问题相关

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" />

猜你喜欢

转载自blog.csdn.net/ysmbdjglww/article/details/80556556