我在表单提交上遇到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 Bad Request
问题是,不调用自定义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);
}
解决方法:
我使用@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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。