未在AJAX(JSON)请求上调用PropertyEditor

时间:2013-01-19 16:24:28

标签: java ajax json spring spring-mvc

我在表单提交时遇到Ajax请求问题。表单包含这些stringify JSON数据:

{"articleContent":"<p>aaa</p>","title":"Po vyplnění titulku aktuality budete","header":"aa","enabled":false,"timestamp":"1358610697521","publishedSince":"03.01.2013 00:00","publishedUntil":"","id":"10"}

当json包含“03.01.2013 00:00”值时,服务器响应 400错误请求

问题是,不会调用自定义DateTimePropertyEditor(使用@InitBinder注册),并且不会传递String格式的DateTime。你有什么想法如何解决这个问题?

控制器映射方法,即处理请求

@RequestMapping( value = "/admin/article/edit/{articleId}", method = RequestMethod.POST, headers = {"content-type=application/json"})
public @ResponseBody JsonResponse  processAjaxUpdate(@RequestBody Article article, @PathVariable Long articleId){
    JsonResponse response = new JsonResponse();
    Article persistedArticle = articleService.getArticleById(articleId);
    if(persistedArticle == null){
        return response;
    }
    List<String> errors = articleValidator.validate(article, persistedArticle);

    if(errors.size() == 0){
        updateArticle(article, persistedArticle);
        response.setStatus(JsonStatus.SUCCESS);
        response.setResult(persistedArticle.getChanged().getMillis());
    }else{
        response.setResult(errors);
    }

    return response;
}

InitBinder

 @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(DateTime.class, this.dateTimeEditor);
        }

3 个答案:

答案 0 :(得分:5)

我使用 @JsonDeserialize

解决了这个问题
@JsonDeserialize(using=DateTimeDeserializer.class)
public DateTime getPublishedUntil() {
    return publishedUntil;
}

我必须实现自定义反序列化器。

    public class DateTimeDeserializer extends StdDeserializer<DateTime> {

    private DateTimeFormatter formatter = DateTimeFormat.forPattern(Constants.DATE_TIME_FORMAT);

    public DateTimeDeserializer(){
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser json, DeserializationContext context) throws IOException, JsonProcessingException {
            try {
                if(StringUtils.isBlank(json.getText())){
                    return null;
                }
                return formatter.parseDateTime(json.getText());
            } catch (ParseException e) {
                return null;
            }
    }
}

答案 1 :(得分:2)

这不是由属性编辑器处理的 - 它在表单字段上而不是在json主体上。要在json中处理非标准日期格式,您必须自定义基础ObjectMapper。假设您使用的是jackson 2.0+,您可以这样做:

一个。使用注释标记publishedSince字段,该注释告诉Object mapper日期的格式 - 基于说明here

public class Article{
    ...
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM.dd.yyyy HH:mm")
    private Date publishedSince;
}

湾或者第二个选项是修改ObjectMapper本身,但这可能是全局的,所以可能不适合你:

public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper(){
        super.setDateFormat(new SimpleDateFormat("MM.dd.yyyy hh:mm"));
    }   
}

并使用Spring MVC进行配置:

<mvc:annotation-driven> 
   <mvc:message-converters register-defaults="true">
       <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
           <property name="objectMapper">
               <bean class="..CustomObjectMapper"/>
           </property>
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

答案 2 :(得分:0)

使用Spring MVC 4.2.1.RELEASE,您需要使用下面的新Jackson2依赖项来使反序列化器工作。

不要使用此

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

改为使用它。

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

也可以使用com.fasterxml.jackson.databind.JsonDeserializer和com.fasterxml.jackson.databind.annotation.JsonDeserialize进行反序列化,而不是使用org.codehaus.jackson中的类