zoukankan      html  css  js  c++  java
  • springboot---->springboot中的格式化(一)

      这里面我们简单的学习一下springboot中关于数据格式化的使用。我以为你不是个好人,没想到你连个坏人都不是。

    springboot中的格式化

    我们的测试环境是springboot,一个将字符串格式化成时间的例子。代码结构如下:

    一、定义我们的字符串格式化器

    package com.linux.huhx.learn.format;
    
    import org.springframework.format.Formatter;
    import org.springframework.stereotype.Component;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 4:16
     * @Desc: formatter的学习
     */
    @Component
    public class DateFormatter implements Formatter<Date> {
        private SimpleDateFormat dateFormat;
    
        @Override
        public Date parse(String text, Locale locale) throws ParseException {
            System.out.println("parse input text: " + text);
            System.out.println("parse date: " + dateFormat.parse(text));
            return dateFormat.parse(text);
        }
    
        public DateFormatter() {
            dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            dateFormat.setLenient(false);
        }
    
        @Override
        public String print(Date object, Locale locale) {
            System.out.println("print method." + object);
            return dateFormat.format(object);
        }
    }

     二、我们的测试控制器类

    package com.linux.huhx.learn.format;
    
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Date;
    
    /**
     * @Author: huhx
     * @Date: 2017-12-15 下午 4:24
     */
    
    @RestController
    @RequestMapping("/formatter")
    public class DateFormatterAction {
    
        @PostMapping("/date")
        public Date formatterStringToDate(Date date) {
            System.out.println("action method: " + date.toString());
            return date;
        }
    }

    使用postman发送post请求:http://localhost:9998/formatter/date。

    返回的数据:以下的时间戳是spring经过转换生成的

    1513311132000

    控制台打印数据:

    parse input text: 20171215121212
    parse date: Fri Dec 15 12:12:12 CST 2017
    action method: Fri Dec 15 12:12:12 CST 2017

    友情链接

  • 相关阅读:
    深入理解java垃圾回收算法
    JVM类加载机制与对象的生命周期
    JVM 类加载机制详解
    从经典面试题看java中类的加载机制
    Intellij IDEA常用快捷键介绍 Intellij IDEA快捷键大全汇总
    Java HashMap 如何正确遍历并删除元素
    记录Java的垃圾回收机制和几种引用
    浅谈jvm中的垃圾回收策略
    Mysql常见四种索引的使用
    Java虚拟机垃圾回收(三) 7种垃圾收集器
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootformatter1.html
Copyright © 2011-2022 走看看