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

    友情链接

  • 相关阅读:
    DiskFileUpload上传与Spring的CommonsMultipartResolver上传对比
    ajax请求jesery接口无法获取参数的问题解决方案
    java乱码问题总结
    indiGolog的安装
    hadoop启动步骤
    ubuntu修改默认jdk
    ubuntu 安装 ssh
    rabbitmq五种模式详解(含实现代码)
    终于可以像使用 Docker 一样丝滑地使用 Containerd 了
    Docker安装Nacos动态服务发现、配置和服务管理平台
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusespringbootformatter1.html
Copyright © 2011-2022 走看看