自定義日期類型的數據綁定 前臺 - 後臺 或 後臺 - 前臺 互相轉換

第一,, 前臺表單中,有一個日期 2014-03-11 提交到後臺類型爲date 時,會報一個轉換類錯誤 如下錯誤

default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'sdate';

因爲springMVC不會自動轉換.

解決辦法 

package com.lanyuan.util;

import java.text.SimpleDateFormat; 
import java.util.Date; 

import org.springframework.beans.propertyeditors.CustomDateEditor; 
import org.springframework.web.bind.WebDataBinder; 
import org.springframework.web.bind.support.WebBindingInitializer; 
import org.springframework.web.context.request.WebRequest; 

/**
 * spring3 mvc 的日期傳遞[前臺-後臺]bug: 
 * org.springframework.validation.BindException 
 * 的解決方式.包括xml的配置 
 *  new SimpleDateFormat("yyyy-MM-dd");  這裏的日期格式必須與提交的日期格式一致
 * @author lanyuan
 * Email:[email protected]
 * date:2014-3-20
 */
public class SpringMVCDateConverter implements WebBindingInitializer { 

  public void initBinder(WebDataBinder binder, WebRequest request) { 
      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");   
      binder.registerCustomEditor(Date.class, new CustomDateEditor(df,true));   
  } 

} 

然後在springmvc的配置文件 spring-servlet.xml 上加一個段,  重點在於紅色字體


<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
		<property name="webBindingInitializer">
			<bean class="com.lanyuan.util.SpringMVCDateConverter" />  <!-- 這裏註冊自定義數據綁定類 -->
		</property>
	</bean>



第二: 後臺回返前臺時, 日期格式是Unix時間戳

例如 後臺data : 2014-03-11 20:22:25  返回前臺json的時間戳是1394508055  很明顯這不是我的要的結果, 我們需要的是 2014-03-11 20:22:25

解決辦法,在controller下新建這個類,然後在javabean的get方法上加上@JsonSerialize(using=JsonDateSerializer.class)

package com.lanyuan.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;

/**
 * springMVC返回json時間格式化
 * 解決SpringMVC使用@ResponseBody返回json時,日期格式默認顯示爲時間戳的問題。
 * 需要在get方法上加上@JsonSerialize(using=JsonDateSerializer.class)
 * @author lanyuan 
 * Email:[email protected] 
 * date:2014-2-17
 */
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {

		String formattedDate = dateFormat.format(date);

		gen.writeString(formattedDate);
	}
}


結語: 前臺 - 後臺  或 後臺 - 前臺 互相轉換 方法有多種,. 這些只是之一,供參考!


參考連接: http://www.micmiu.com/j2ee/spring/springmvc-binding-date/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章