Spring MVC前、后台Daate类型相互转换问题
一、后台到前台的Date转换
解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳,而不是时间的问题,即,需要显示的时间是2015-07-09 10:24:27,却显示的是类似140000231的数字,这个就是JSon的时间戳了。
解决办法:
新建一个类,然后在javabean的get方法上加上@JsonSerialize(using=com.***.**.JsonDateSerializer.class)
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;
/**
* @author sunyar
*
*/
/**
* springMVC返回json时间格式化 解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题。
* 需要在get方法上加上@JsonSerialize(using=com.***.**.JsonDateSerializer.class)
*/
@Component
public class JsonDateSerializer extends JsonSerializer<Date> {
public JsonDateSerializer() {
super();
}
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);
}
}
注:此处在ger方法处可能会报 com.***.**.JsonDateSerializer.class can not be resolved to a type。
首先,如果直接JsonDateSerializer.class,要注意有没有引入该类的包。
其次,注意重新build一下。
二、从前台到后台的Date类型转换
前台表单中,有一个日期 2015-07-21 提交到后台类型为Date 时,会报一个转换类错误 如下错误
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'sdate';
因为springMVC不会自动转换.
解决办法:
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;
/**
* org.springframework.validation.BindException
* 的解决方式.包括xml的配置
* new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 这里的日期格式必须与提交的日期格式一致
*/
public class SpringMVCDateConverter implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(df,true));
}
}
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
<span style="color:#ff0000;"><property name="webBindingInitializer">
<bean class="com.lanyuan.util.SpringMVCDateConverter" /> <!-- 这里注册自定义数据绑定类 -->
</property></span>
</bean>
参考链接:http://blog.csdn.net/mmm333zzz/article/details/21696653

浙公网安备 33010602011771号