Spring 3.0异常在POST上将String转换为java.util.Date

Ste*_*per 4 spring json date smartgwt java.util.date

我希望有人可以帮助我,因为我已经在一个看起来很简单并且已经在网络上的其他主题中记录的问题上撞墙几天.

我正在使用Smart GWT客户端(3.0)与Spring 3.1服务器并使用JSON进行通信(使用Jackson API 1.9).

问题是,当我尝试从SmartGWT客户端保存日期并将其发送到服务器时,我得到以下异常:

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'comment' on field 'dateAdded': rejected value [2012-06-27T10:57:47+0100]; codes [typeMismatch.comment.dateAdded,typeMismatch.dateAdded,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [comment.dateAdded,dateAdded]; arguments []; default message [dateAdded]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateAdded'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2012-06-27T10:57:47+0100'; nested exception is java.lang.IllegalArgumentException] at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110)

我在其他一些帖子中看到过这个问题,但大多数都与没有以正确格式格式化日期有关,但我尝试了各种格式: - yyyy-MM-dd - yyyy-MM-dd'T'HH:mm :ssZ - yyyyMMddHHmmssZ(根据建议:http://code.google.com/p/usersapi/issues/detail?id = 8)

所以在我的代码中我做了以下事情:

  1. 配置CustomObjectMapper:

`public class CustomObjectMapper extends ObjectMapper {

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

public CustomObjectMapper() {
    super();
    configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    setDateFormat(formatter);
    getDeserializationConfig().setDateFormat(formatter);
}
Run Code Online (Sandbox Code Playgroud)

}

  1. 因此Spring应用程序上下文:

`

<mvc:annotation-driven>
    <mvc:message-converters>            
        <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
            <constructor-arg ref="jaxbMarshaller" />
            <property name="supportedMediaTypes" value="application/xml"/>
        </bean>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
            <property name="supportedMediaTypes" value="application/json" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<context:component-scan base-package="com.jpmorgan.creditriskreporting.server" />

<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="jaxbMarshaller" />
    <property name="supportedMediaTypes" value="application/xml"/>
</bean>


<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    <property name="objectMapper" ref="jacksonObjectMapper" />
</bean>


<bean id="jacksonObjectMapper" class="com.jpmorgan.creditriskreporting.server.util.CustomObjectMapper" />


<!-- Client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>
            <ref bean="marshallingConverter" />
            <ref bean="jsonConverter" />
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

`

  1. Bean对象:

`import java.util.Date;

@JsonAutoDetect public class Comment {

private int id;
private String comment;
private Date dateAdded;

public Comment() {}

public Comment(int id) {
    this.id = id;
}
Run Code Online (Sandbox Code Playgroud)

...

//@JsonSerialize(using=JsonDateSerializer.class) -- I had previously tried to use these custom Date serializer class
public Date getDateAdded() {
    return dateAdded;
}
//@JsonDeserialize(using=JsonDateDeserializer.class)
public void setDateAdded(Date dateAdded) {
    this.dateAdded = dateAdded;
}
Run Code Online (Sandbox Code Playgroud)

`

编辑:

  1. 控制器类

这可能是问题所在,因为当我使用@RequestBody时,它可以从我的集成测试中运行,但是,SmartGWT中的Abstract RestDataSource只能与@ModelAttribute一起使用,所以我不知道如何继续.

@RequestMapping(value="/", method=RequestMethod.POST) public @ResponseBody Comment createNewComment2(@ModelAttribute Comment comment) { log.info("calling createComment with comment: {}", comment); comment.setDateAdded(new Date()); Comment added = commentDao.create(comment); log.info("created comment: {}", added); return commentDao.get(comment);
}

所以我可以从服务器获取数据,日期显示在SmartGWT中.只有当我添加数据时才会出现问题.来自Smart GWT Developer Console:

{ "dataSource":"CommentDS", "operationType":"add", "componentId":"isc_DynamicForm_1", "data":{ "userAdded":"sharper", "dateAdded":"2012-06-27T10:57:47+0100", "comment":"sample" }, "callback":{ "target":[DynamicForm ID:isc_DynamicForm_1], "methodName":"saveEditorReply" }, "showPrompt":true, "prompt":"Saving form...", "oldValues":{ }, "clientContext":{ }, "requestId":"CommentDS$6272" }

对此有任何帮助非常感谢.

干杯,史蒂夫

Ste*_*per 11

我发现这个问题归功于http://vkubushyn.wordpress.com/2011/05/31/smart-gwt-restful-spring-mvc

不得不使用Spring的InitBinder

@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }


ege*_*men 5

您应该将DateFormat添加到模型中。

@DateTimeFormat(pattern = "dd.MM.yyyy")
private Date beginDate;
@DateTimeFormat(pattern = "dd.MM.yyyy")
private Date endDate;
Run Code Online (Sandbox Code Playgroud)

作为功​​能参数

 void  functionName** (@RequestParam("beginDate") @DateTimeFormat(pattern = "dd.MM.yyyy")Date beginDate, @RequestParam("endDate") @DateTimeFormat(pattern = "dd.MM.yyyy")Date endDate)
Run Code Online (Sandbox Code Playgroud)