失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > springboot前端传参date类型后台处理方式

springboot前端传参date类型后台处理方式

时间:2019-01-10 21:07:40

相关推荐

springboot前端传参date类型后台处理方式

springboot前端传参date类型后台处理方式

先说结论:建议大家直接使用@JsonFormat,原因如下:

1、针对json格式:在配置文件中加以下配置

spring.jackson.date-format=yyyy-MM-dd HH:mm:ssspring.jackson.time-zone=GMT+8

2、针对form表单格式,加下面这句配置就可以

spring.mvc.dateFormat = yyyy-MM-dd HH:mm:ss

3、也可以在pojo中对特定的date类型属性加了以下配置

@DateTimeFormat来控制入参,@JsonFormat来控制出参@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")

4、前端以字符串的形式给后台传递带有格式的 日期 和 数字 数据,导致后台无法解析数据:

解决方法:

总结:

1.如果前后端传的数据都是json格式,那么后台接数据,传数据都可以用@JsonFormat ;

2.@DateTimeFormat适合后端接收前端传来的数据,不管是不是json格式都可以正确转换成Date型数据,只要前端传来的格式正确且后端@DateTimeFormat的pattern写正确。但是,这个注解无法将Date型数据用json传到前端去

综上所述,建议大家直接使用@JsonFormat

Springboot的bean实体类接收Date类型

@GetMapping("/test")public ResponseResult docList(QueryListParam queryListParam) {return testService.queryList(queryListParam);}

@Datapublic class QueryListParam implements Serializable {/*** 姓名*/private String name;/*** 起始时间(接收不到,会报错)*/private Date startTime;/*** 结束时间(接收不到,会报错)*/private Date endTime;}

GET请求直接传递 startTime=-01-01 01:10:00 是接收不到了,后台会报错,需要在bean中Date类型的属性上添加注解@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)

该注解是org.springframework.format.annotation下的

@Datapublic class QueryListParam implements Serializable {/*** 姓名*/private String name;/*** 起始时间,接收成功*/@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date startTime;/*** 结束时间,接收成功*/@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date endTime;}

但是不用这种方法,用String进行接收,在用SimpleDateFormat进行转换。

如果觉得《springboot前端传参date类型后台处理方式》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。