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

    友情链接

  • 相关阅读:
    linux下进程权限分析
    基于Token的身份验证——JWT
    hadoop2.7.3+spark2.1.0+scala2.12.1环境搭建(3)http://www.cnblogs.com/liugh/p/6624491.html
    hadoop2.7.3+spark2.1.0+scala2.12.1环境搭建(2)安装hadoop
    hadoop2.7.3+spark2.1.0+scala2.12.1环境搭建(1)安装jdk
    配置ssh无密钥登陆
    Linux实战案例(7)安装jdk
    Scala入门(1)Linux下Scala(2.12.1)安装
    Linux实战案例(6)yum查找、卸载、和安装软件
    Linux实战案例(5)关闭Centos的防火墙
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootformatter1.html
Copyright © 2011-2022 走看看