ssm后台接收前台Date类型参数格式的问题

在使用springmvc @RequestBody来接收Date类型参数的时候,当格式不对的时候总会出现异常。给大家推荐几种方法:

1.当你接收yyyy-MM-dd格式的日期时,只需要在实体类中相应的字段上面加上@DateTimeFormat(pattern = “yyyy-MM-dd”)注解即可。

2.当你接收yyyy-MM-dd HH:mm:ss格式的日期时,用上面的方面就不行了,而且会报异常,因为上面的方法只是会转换指定的几种格式的Date类型,具体哪几种格式可以查看抛出的异常,异常中有详细的说明。

这时需要使用@JsonFormat(pattern=”yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)注解了。这时就会自动转换成该格式的注解。

3.最后这种方法,我试了不行,但是好多人说可以,不知道是怎么弄的,在这里也跟大家说说。就是在controller里面中的一个方法加上@InitBinder注解,例子如下:

@InitBinder
 public void initBinder(WebDataBinder binder) {
  DateFormat sdf_yyyyMMdd_hhmmss = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
  sdf_yyyyMMdd_hhmmss.setLenient(false);

  binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf_yyyyMMdd_hhmmss, true));
  binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class,true));
  binder.registerCustomEditor(String.class,new StringTrimmerEditor(false));
  binder.registerCustomEditor(Long.class,new CustomNumberEditor(Long.class,true));
 }

我自己认为,如果是用@RequestBody来接收参数,这个方法不行,我试过的。这个方法会在到达Controller之前先调用,至于别人怎么用的可以,我就不清楚了。总之第二种方法是既简单,又方便。所以推荐使用第二种方法。

@DateTimeFormat(pattern="yyyy-MM-dd")        例如:2018-3-15

    private Date startTime;

 @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")   
    private Date updateTime;

猜你喜欢

转载自blog.csdn.net/zalan01408980/article/details/82912345
今日推荐