我正在使用带注释的Spring 3.1 MVC代码(spring-mvc),当我通过@RequestBody发送日期对象时,日期显示为数字。这是我的控制器
@Controller @RequestMapping("/test") public class MyController { @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); } @RequestMapping(value = "/getdate", method = RequestMethod.GET) public @ResponseBody Date getDate(@RequestParam("dt") Date dt, Model model) { // dt is properly constructed here.. return new Date(); } }
当我传递日期时,我能够以格式接收日期。但是我的浏览器将日期显示为数字
1327682374011
如何以我为Webbinder注册的格式显示日期?我在某个论坛上看到我应该使用杰克逊映射器,但是我不能更改现有的映射器吗?
为了覆盖Jakson的默认日期格式策略,请遵循以下步骤:
JsonSerializer
serialize(Date date, JsonGenerator gen, SerializerProvider provider)
@JsonSerialize(using = CustomDateSerializer.class)
//CustomDateSerializer class public class CustomDateSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatter.format(value); gen.writeString(formattedDate); } } //date getter method @JsonSerialize(using = CustomDateSerializer.class) public Date getDate() { return date; }