经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
springboot?接收LocalDateTime方式
来源:jb51  时间:2022/7/4 14:09:45  对本文有异议

本文基于jdk8。

1.标准日期格式转换

本类型是指前端传递类似"yyyy-MM-dd HH:mm:ss"格式字符串,后端以 LocalDateTime类型接收。

spring默认的使用jackson,故添加maven依赖,可参考官方文档

  1. <dependency>
  2. ? ? <groupId>com.fasterxml.jackson.module</groupId>
  3. ? ? <artifactId>jackson-module-parameter-names</artifactId>
  4. </dependency>
  5. <dependency>
  6. ? ? <groupId>com.fasterxml.jackson.datatype</groupId>
  7. ? ? <artifactId>jackson-datatype-jdk8</artifactId>
  8. </dependency>
  9. <dependency>
  10. ? ? <groupId>com.fasterxml.jackson.datatype</groupId>
  11. ? ? <artifactId>jackson-datatype-jsr310</artifactId>
  12. </dependency>

添加一个配置类

  1. @Configuration
  2. public class DateConfiguration {
  3. ?? ?@Bean
  4. ?? ?public ObjectMapper objectMapper(){
  5. ?? ??? ?return new ObjectMapper()
  6. ?? ??? ??? ??? ?.registerModule(new ParameterNamesModule())
  7. ?? ??? ??? ??? ?.registerModule(new Jdk8Module())
  8. ?? ??? ??? ??? ?.registerModule(new JavaTimeModule());
  9. ?? ?}
  10. }

基础配置完成,使用时在对应字段添加@DateTimeFormat 进行反序列化或者@JsonFormat序列化。

2.非json请求时间戳转换

本类型指在前端非json请求,传递参数为时间戳,然后转为LocalDateTime。

可在上文基础上添加配置,示例如下:

  1. @Configuration
  2. public class DateConfiguration {
  3. ?? ?@Bean
  4. ?? ?public ObjectMapper objectMapper(){
  5. ?? ??? ?return new ObjectMapper()
  6. ?? ??? ??? ??? ?.registerModule(new ParameterNamesModule())
  7. ?? ??? ??? ??? ?.registerModule(new Jdk8Module())
  8. ?? ??? ??? ??? ?.registerModule(new JavaTimeModule());
  9. ?? ?}
  10. ? ? @Bean
  11. ? ? public Formatter<LocalDateTime> localDateTimeFormatter() {
  12. ? ? ? ? return new Formatter<LocalDateTime>() {
  13. ? ? ? ? ? ? @Override
  14. ? ? ? ? ? ? public LocalDateTime parse(String text, Locale locale) ?{
  15. ? ? ? ? ? ? ? ? return Instant
  16. ? ? ? ? ? ? ? ? ? ? ? ? .ofEpochMilli(Long.parseLong(text))
  17. ? ? ? ? ? ? ? ? ? ? ? ? .atZone(ZoneOffset.ofHours(8))
  18. ? ? ? ? ? ? ? ? ? ? ? ? .toLocalDateTime();
  19. ? ? ? ? ? ? }
  20. ? ? ? ? ? ? @Override
  21. ? ? ? ? ? ? public String print(LocalDateTime object, Locale locale) {
  22. ? ? ? ? ? ? ? ? return DateTimeFormatter.ISO_DATE.format(object);
  23. ? ? ? ? ? ? }
  24. ? ? ? ? };
  25. ? ? }
  26. }

3.json请求时间戳转换

本类型指在前端json请求,传递参数为时间戳,然后转为LocalDateTime。

1.自定义解析注解

  1. @Retention (RetentionPolicy.RUNTIME)
  2. @JacksonAnnotationsInside
  3. @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
  4. public @interface StampToLocalDateTime {
  5. }

2.自定义解析类

  1. public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> ?{
  2. ? ? @Override
  3. ? ? public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException{
  4. ? ? ? ? if (StringUtils.isEmpty(jsonParser.getText())) {
  5. ? ? ? ? ? ? return null;
  6. ? ? ? ? }
  7. ? ? ? ? return Instant
  8. ? ? ? ? ? ? ? ? .ofEpochMilli(Long.parseLong(jsonParser.getText()))
  9. ? ? ? ? ? ? ? ? .atZone(ZoneOffset.ofHours(8))
  10. ? ? ? ? ? ? ? ? .toLocalDateTime();
  11. ? ? }
  12. }

在需要使用的字段添加@StampToLocalDateTime即可。示例如下

  1. public class DemoReq ?{
  2. ?? ?
  3. ?? ?@StampToLocalDateTime
  4. ? ? private LocalDateTime signTime;
  5. }

4.序列化扩展

有时返回前端数据,要包装下信息(比如返回全路径地址及某些参数),直接硬编码不够优雅。这时可以通过序列化操作,实现ContextualSerializer接口,要进行一些额外操作,。

1.自定义注解

  1. @Retention (RetentionPolicy.RUNTIME)
  2. @JacksonAnnotationsInside
  3. @JsonSerializer(using = FullUrlSerializer.class)
  4. public @interface FullUrl {
  5. ??? ?String value() default "";
  6. }

2.自定义序列类

  1. public class FullUrlSerializer extends JsonSerializer<String> implements ContextualSerializer {
  2. ? ? private String params;
  3. ? ? @Value("${domain}")
  4. ? ? private String domain;
  5. ? ? public FullUrlSerializer() {
  6. ? ? }
  7. ? ? public FullUrlSerializer(String params) {
  8. ? ? ? ? this.params = params;
  9. ? ? }
  10. ? ? @Override
  11. ? ? public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
  12. ? ? ? ? if (property == null) {
  13. ? ? ? ? ? ? return prov.findNullValueSerializer(null);
  14. ? ? ? ? }
  15. ? ? ? ? if (Objects.equals(property.getType().getRawClass(), String.class)) {
  16. ? ? ? ? ? ? FullUrl fullUrl = property.getAnnotation(FullUrl.class);
  17. ? ? ? ? ? ? if (fullUrl == null) {
  18. ? ? ? ? ? ? ? ? fullUrl = property.getContextAnnotation(FullUrl.class);
  19. ? ? ? ? ? ? }
  20. ? ? ? ? ? ? if (fullUrl != null) {
  21. ? ? ? ? ? ? ? ? return new FullUrlSerializer(fullUrl.value());
  22. ? ? ? ? ? ? }
  23. ? ? ? ? }
  24. ? ? ? ? return prov.findValueSerializer(property.getType(), property);
  25. ? ? }
  26. ? ? @Override
  27. ? ? public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  28. ? ? ? ? String url = "";
  29. ? ? ? ? if (!StringUtils.isEmpty(value)) {
  30. ? ? ? ? ? ? url = domain.concat(value);
  31. ? ? ? ? ? ? if (!StringUtils.isEmpty(params)) {
  32. ? ? ? ? ? ? ? ? url.contains(params);
  33. ? ? ? ? ? ? }
  34. ? ? ? ? }
  35. ? ? ? ? gen.writeString (url);
  36. ? ? }
  37. }

5.swagger支持

要使swagger支持LocalDateTime等类型可以设置directModelSubstitute,示例如下:

  1. @Configuration
  2. public abstract class SwaggerConfiguration {
  3. ?? ?@Bean
  4. ?? ?public Docket createRestApi() {
  5. ?? ??? ?return new Docket(DocumentationType.SWAGGER_2)
  6. ?? ??? ??? ??? ?.directModelSubstitute(LocalDateTime.class,String.class)
  7. ?? ??? ??? ??? ?.directModelSubstitute(LocalDate.class, String.class)
  8. ?? ??? ??? ??? ?.directModelSubstitute(LocalTime.class, String.class)
  9. ?? ??? ??? ??? ?.directModelSubstitute(ZonedDateTime.class,String.class)
  10. ?? ??? ??? ??? ?.build();
  11. ?? ?}
  12. }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号