第一,, 前台表单中,有一个日期 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:mmm333zzz520@163.com
* 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 上加一个段, 重点在于红色字体
class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>
第二: 后台回返前台时, 日期格式是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:mmm333zzz520@163.com
* date:2014-2-17
*/
@Component
public class JsonDateSerializer extends JsonSerializer{
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://blog.csdn.net/mmm333zzz/article/details/21696653
SpringMVC自定义日期类型的数据绑定
目录:
应用场景
实现方法
[一]、应用场景
在实际应用中,经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换,一般页面输入的日志格式为:yyyy-MM-dd ,而SpringMVC中默认不支持这样的格式转换,所以需要我们自定义数据类型的绑定才能实现这个功能。
[二]、实现方法
利用 WebBindingInitializer 注册自定义日期转换控制器。
自定义日期转换器:MyDataBinding.java
package com.micmiu.demo.web.v1.utils;
import java.text.SimpleDateFormat;
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;
/**
* 自定义日期、时间的类型绑定
*
* @author <a href=”http://www.micmiu.com”>Michael Sun</a>
*/
public class MyDataBinding implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
dateFormat.setLenient(false);
SimpleDateFormat datetimeFormat = new SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);
datetimeFormat.setLenient(false);
binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(
dateFormat, true));
binder.registerCustomEditor(java.sql.Timestamp.class,
new CustomTimestampEditor(datetimeFormat, true));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.micmiu.demo.web.v1.utils;
import java.text.SimpleDateFormat;
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;
/**
* 自定义日期、时间的类型绑定
*
* @author <a href=”http://www.micmiu.com”>Michael Sun</a>
*/
publicclassMyDataBindingimplementsWebBindingInitializer{
publicvoidinitBinder(WebDataBinder binder,WebRequest request){
SimpleDateFormat dateFormat=newSimpleDateFormat(“yyyy-MM-dd”);
dateFormat.setLenient(false);
SimpleDateFormat datetimeFormat=newSimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);
datetimeFormat.setLenient(false);
binder.registerCustomEditor(java.util.Date.class,newCustomDateEditor(
dateFormat,true));
binder.registerCustomEditor(java.sql.Timestamp.class,
newCustomTimestampEditor(datetimeFormat,true));
}
}
Timestamp 的实现:CustomTimestampEditor.java
package com.micmiu.demo.web.v1.utils;
import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.springframework.util.StringUtils;
import java.text.ParseException;
/**
* Property editor for <code>java.sql.Timestamp</code>,<br>
* supporting a custom <code>java.text.DateFormat</code>.
*
* @author <a href=”http://www.micmiu.com”>Michael Sun</a>
*/
public class CustomTimestampEditor extends PropertyEditorSupport {
private final SimpleDateFormat dateFormat;
private final boolean allowEmpty;
private final int exactDateLength;
public CustomTimestampEditor(SimpleDateFormat dateFormat, boolean allowEmpty) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.exactDateLength = -1;
}
public CustomTimestampEditor(SimpleDateFormat dateFormat,
boolean allowEmpty, int exactDateLength) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.exactDateLength = exactDateLength;
}
public void setAsText(String text) throws IllegalArgumentException {
if ((this.allowEmpty) && (!(StringUtils.hasText(text)))) {
setValue(null);
} else {
if ((text != null) && (this.exactDateLength >= 0)
&& (text.length() != this.exactDateLength)) {
throw new IllegalArgumentException(
“Could not parse date: it is not exactly”
+ this.exactDateLength + “characters long”);
}
try {
setValue(new Timestamp(this.dateFormat.parse(text).getTime()));
} catch (ParseException ex) {
throw new IllegalArgumentException(“Could not parse date: ”
+ ex.getMessage(), ex);
}
}
}
public String getAsText() {
Timestamp value = (Timestamp) getValue();
return ((value != null) ? this.dateFormat.format(value) : “”);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
packagecom.micmiu.demo.web.v1.utils;
import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.springframework.util.StringUtils;
import java.text.ParseException;
/**
* Property editor for <code>java.sql.Timestamp</code>,<br>
* supporting a custom <code>java.text.DateFormat</code>.
*
* @author <a href=”http://www.micmiu.com”>Michael Sun</a>
*/
publicclassCustomTimestampEditorextendsPropertyEditorSupport{
privatefinalSimpleDateFormat dateFormat;
privatefinalbooleanallowEmpty;
privatefinalintexactDateLength;
publicCustomTimestampEditor(SimpleDateFormat dateFormat,booleanallowEmpty){
this.dateFormat=dateFormat;
this.allowEmpty=allowEmpty;
this.exactDateLength=-1;
}
publicCustomTimestampEditor(SimpleDateFormat dateFormat,
booleanallowEmpty,intexactDateLength){
this.dateFormat=dateFormat;
this.allowEmpty=allowEmpty;
this.exactDateLength=exactDateLength;
}
publicvoidsetAsText(Stringtext)throwsIllegalArgumentException{
if((this.allowEmpty)&&(!(StringUtils.hasText(text)))){
setValue(null);
}else{
if((text!=null)&&(this.exactDateLength>=0)
&&(text.length()!=this.exactDateLength)){
thrownewIllegalArgumentException(
“Could not parse date: it is not exactly”
+this.exactDateLength+”characters long”);
}
try{
setValue(newTimestamp(this.dateFormat.parse(text).getTime()));
}catch(ParseException ex){
thrownewIllegalArgumentException(“Could not parse date: ”
+ex.getMessage(),ex);
}
}
}
publicStringgetAsText(){
Timestamp value=(Timestamp)getValue();
return((value!=null)?this.dateFormat.format(value):””);
}
}
修改spring-mvc 的配置文件,添加 webBindingInitializer 属性的注入配置:
XHTML
class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”>
class=”org.springframework.http.converter.ByteArrayHttpMessageConverter” />
class=”org.springframework.http.converter.StringHttpMessageConverter”>
text/plain;charset=UTF-8
*/*;charset=UTF-8
class=”org.springframework.http.converter.xml.SourceHttpMessageConverter” />
class=”org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter” />
class=”org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”>
class=”org.springframework.http.converter.ByteArrayHttpMessageConverter”/>
class=”org.springframework.http.converter.StringHttpMessageConverter”>
text/plain;charset=UTF-8
*/*;charset=UTF-8
class=”org.springframework.http.converter.xml.SourceHttpMessageConverter”/>
class=”org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter”/>
class=”org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”>
这样就可以实现表单中的字符串自动转换为Date或者Timestamp 类型。
转自http://www.micmiu.com/j2ee/spring/springmvc-binding-date/