zoukankan      html  css  js  c++  java
  • SpringBoot配置自定义日期参数转换器

    1.自定义参数转换器

    自定义参数转换器必须实现Converter接口

     1 /**
     2  * Created by IntelliJ IDEA.
     3  *
     4  * @Auther: ShaoHsiung
     5  * @Date: 2018/8/29 15:42
     6  * @Title:
     7  * @Description: 自定义日期转换器
     8  */
     9 public class DateConverter implements Converter<String,Date> {
    10     private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    11     @Override
    12     public Date convert(String s) {
    13         if ("".equals(s) || s == null) {
    14             return null;
    15         }
    16         try {
    17             return simpleDateFormat.parse(s);
    18         } catch (ParseException e) {
    19             e.printStackTrace();
    20         }
    21         return null;
    22     }
    23 }

    2.配置转换器

    自定义WebMvcConfig继承WebMvcConfigurerAdapter,在addFormatters方法中进行配置:

     1 /**
     2  * Created by IntelliJ IDEA.
     3  *
     4  * @Auther: ShaoHsiung
     5  * @Date: 2018/8/29 15:41
     6  * @Title:
     7  * @Description:
     8  */
     9 @Configuration
    10 public class WebMvcConfig extends WebMvcConfigurerAdapter {
    11     @Override
    12     public void addFormatters(FormatterRegistry registry) {
    13         registry.addConverter(new DateConverter());
    14     }
    15 }

    3.编写测试controller

     1 /**
     2  * Created by IntelliJ IDEA.
     3  *
     4  * @Auther: ShaoHsiung
     5  * @Date: 2018/8/29 11:14
     6  * @Title: 
     7  * @Description: 测试日期转换器
     8  */
     9 @RestController
    10 public class HelloController {
    11     @RequestMapping(method = RequestMethod.GET, path = "/hello")
    12     public String hello(Date date) {
    13         // 测试简单类型
    14         System.out.println(date);
    15         
    16         return "Hello SpringBoot";
    17     }
    18 }

    4.测试方式和效果

  • 相关阅读:
    学习笔记65—学位和学历区别
    学习笔记64—兴趣阅读之文学
    学习笔记63—兴趣阅读之法律
    学习笔记62—兴趣阅读之管理学
    学习笔记61—兴趣阅读之经济学
    学习笔记60—SPSS
    学习笔记59—收藏这7个在线配色神器,再也不愁配色灵感了
    学习笔记58—3D杯子设计
    网络处理2-异步POST请求和同步请求
    网络处理1-异步GET请求
  • 原文地址:https://www.cnblogs.com/shaohsiung/p/9554895.html
Copyright © 2011-2022 走看看