spring-boot前端参数单位转换

前端时间单位用的是unix时间戳,单位秒,而java后端用的是Date类型。
在request请求时,如何把前端的时间戳类型优雅的转换为后端的Date类型呢。

如果你想在response时,把后端的Date类型转换到前端的时间戳类型
可以看这篇文章java中JsonSerializer用法,前后端单位转换必备

这里我使用的是SpringBoot框架。

Controller代码

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid OrderForm form,
                      BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {

        }

OrderForm对象

@Data
public class OrderForm {

    private String id;

    private String userName;

    private Date addTime;
}

这时,如果直接传addTime=1488264066是会报错的,提示类型不正确。
但如果你把addTime类型改成Long就可以

@Data
public class OrderForm {

    private String id;

    private String userName;

    private Long addTime;
}

说明spring已经帮我们做了String到Long的转换,但是没有做转换到Date类型。
我们来扩展即可。

在src/java/下建一个名字为bind的包。
下面放这3个java文件

/**
* 扩展类型转换
*/
public class CustomDateEditor extends PropertyEditorSupport {

    /**
     * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        setValue(new Date(Long.decode(text)));
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? String.valueOf(TimeUnit.MILLISECONDS.toSeconds(value.getTime())) : "");
    }

}
/**
* 扩展web初始化的配置
*/
public class CustomDateWebBindingInitializer implements WebBindingInitializer {

    /**
     * @see org.springframework.web.bind.support.WebBindingInitializer#initBinder(org.springframework.web.bind.WebDataBinder,
     *      org.springframework.web.context.request.WebRequest)
     */
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor());
    }

}
/**
* 让配置在request请求时生效
*/
@Configuration
public class CustomDateEditorConfiguration {

    @Autowired
    public void setWebBindingInitializer(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        requestMappingHandlerAdapter.setWebBindingInitializer(new CustomDateWebBindingInitializer());
    }
}

配置好后,就可以接收到Date类型的内容了,全局生效。

作者:nul1
链接:https://www.jianshu.com/p/3a5fc2564501
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Java中

    //-----------------------------------------------------------------------
    /**
     * The ISO date-time formatter that formats or parses a date-time with an
     * offset, such as ‘2011-12-03T10:15:30+01:00‘.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 extended offset date-time format.
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_LOCAL_DATE_TIME}
     * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
     *  they will be handled even though this is not part of the ISO-8601 standard.
     *  Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has a chronology of ISO set to ensure dates in
     * other calendar systems are correctly converted.
     * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
    static {
        ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE_TIME)
                .appendOffsetId()
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }
    //-----------------------------------------------------------------------
    /**
     * The ISO date-time formatter that formats or parses a date-time with an
     * offset, such as ‘2011-12-03T10:15:30+01:00‘.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 extended offset date-time format.
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_LOCAL_DATE_TIME}
     * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
     *  they will be handled even though this is not part of the ISO-8601 standard.
     *  Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has a chronology of ISO set to ensure dates in
     * other calendar systems are correctly converted.
     * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
    static {
        ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE_TIME)
                .appendOffsetId()
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }
    //-----------------------------------------------------------------------
    /**
     * The ISO instant formatter that formats or parses an instant in UTC,
     * such as ‘2011-12-03T10:15:30Z‘.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 instant format.
     * When formatting, the second-of-minute is always output.
     * The nano-of-second outputs zero, three, six or nine digits digits as necessary.
     * When parsing, time to at least the seconds field is required.
     * Fractional seconds from zero to nine are parsed.
     * The localized decimal style is not used.
     * <p>
     * This is a special case formatter intended to allow a human readable form
     * of an {@link java.time.Instant}. The {@code Instant} class is designed to
     * only represent a point in time and internally stores a value in nanoseconds
     * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be
     * formatted as a date or time without providing some form of time-zone.
     * This formatter allows the {@code Instant} to be formatted, by providing
     * a suitable conversion using {@code ZoneOffset.UTC}.
     * <p>
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from
     *  {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND}
     *  using the {@code UTC} offset. Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has no override chronology or zone.
     * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_INSTANT;
    static {
        ISO_INSTANT = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendInstant()
                .toFormatter(ResolverStyle.STRICT, null);
    }

java.time.format.DateTimeFormatter#ISO_INSTANT

Customizing Formats


Version note: This Date and Time section uses the date and time APIs in the java.util package. The java.time APIs, available in the JDK 8 release, provides a comprehensive date and time model that offers significant improvements over the java.util classes. The java.time APIs are described in the Date Time trail. The Legacy Date-Time Code page might be of particular interest.


The previous section, Using Predefined Formats, described the formatting styles provided by the DateFormat class. In most cases these predefined formats are adequate. However, if you want to create your own customized formats, you can use the SimpleDateFormat class.

The code examples that follow demonstrate the methods of the SimpleDateFormat class. You can find the full source code for the examples in the file named SimpleDateFormatDemo.

About Patterns

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time. For a full description of the pattern‘s syntax, see the tables in Date Format Pattern Syntax.

The following code formats a date and time according to the pattern String passed to the SimpleDateFormat constructor. The String returned by the format method contains the formatted date and time that are to be displayed.

Date today;
String output;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);
System.out.println(pattern + " " + output);

The following table shows the output generated by the previous code example when the U.S. Locale is specified:

Customized Date and Time Formats
Pattern Output
dd.MM.yy 30.06.09
yyyy.MM.dd G ‘at‘ hh:mm:ss z 2009.06.30 AD at 08:29:36 PDT
EEE, MMM d, ‘‘yy Tue, Jun 30, ‘09
h:mm a 8:29 PM
H:mm 8:29
H:mm:ss:SSS 8:28:36:249
K:mm a,z 8:29 AM,PDT
yyyy.MMMMM.dd GGG hh:mm aaa 2009.June.30 AD 08:29 AM

Patterns and Locale

The SimpleDateFormat class is locale-sensitive. If you instantiate SimpleDateFormat without a Locale parameter, it will format the date and time according to the default Locale. Both the pattern and the Locale determine the format. For the same pattern, SimpleDateFormat may format a date and time differently if the Locale varies.

In the example code that follows, the pattern is hardcoded in the statement that creates the SimpleDateFormat object:

Date today;
String result;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
today = new Date();
result = formatter.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);

When the currentLocale is set to different values, the preceding code example generates this output:

Locale: fr_FR
Result: mar. 30 juin 09
Locale: de_DE
Result: Di 30 Jun 09
Locale: en_US
Result: Tue 30 Jun 09

Date Format Pattern Syntax

You can design your own format patterns for dates and times from the list of symbols in the following table:

Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
escape for text Delimiter (none)
single quote Literal

Characters that are not letters are treated as quoted text. That is, they will appear in the formatted text even if they are not enclosed within single quotes.

The number of symbol letters you specify also determines the format. For example, if the "zz" pattern results in "PDT," then the "zzzz" pattern generates "Pacific Daylight Time." The following table summarizes these rules:

Presentation Number of Symbols Result
Text 1 - 3 abbreviated form, if one exists
Text >= 4 full form
Number minimum number of digits is required shorter numbers are padded with zeros (for a year, if the count of ‘y‘ is 2, then the year is truncated to 2 digits)
Text & Number 1 - 2 number form
Text & Number 3 text form

原文地址:https://www.cnblogs.com/softidea/p/10192467.html

时间: 2024-10-06 21:02:44

spring-boot前端参数单位转换的相关文章

spring boot 2.* 参数接收

测试环境:spring boot 2.1.0/*//数组和参数同时传递需要借助实体类实现//接收json@RequestMapping(value = "test3",method = RequestMethod.POST)public String test3(@RequestBody String obj){ System.out.println(obj); return "1";}//接收数组@RequestMapping(value = "test

spring boot 之参数

spring.config.name指的是spring boot启动的入口配置文件.默认是application.properties/yaml/yml.如:java -jar xxx.jar --spring.config.name=myApplication; spring.config.location作用与spring.config.name一样.但是,要比spring.config.name指定的更多.它可以指定多个启动配置,同时也可以指定path和文件名.如:java -jar xx

spring-boot实战【08】【转】:Spring Boot属性配置文件详解

相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在application.properties中完成一些属性配置就能开启各模块的应用. 在之前的各篇文章中都有提及关于application.pro

spring boot 1.5.4 配置文件详解(八)

上一篇:spring boot 1.5.4 集成spring-Data-JPA(七) 1      Spring Boot配置文件详解 相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在appli

Spring Cloud Spring Boot mybatis分布式微服务云架构(三)属性配置文件详解(1)

相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在application.properties中完成一些属性配置就能开启各模块的应用. 在之前的各篇文章中都有提及关于application.pro

(拿来主义-8) Spring Boot属性配置文件详解(三)

相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在application.properties中完成一些属性配置就能开启各模块的应用. 自定义属性与加载 我们在使用Spring Boot的时候,通

spring boot 源码解析52-actuate中MVCEndPoint解析

今天有个bie项目的jolokia的endpoint不能访问,调试源码发现:endpoint.enabled的开关导致的. 前言之前的几篇文章分析了spring boot 中有关endpoint的实现,细心的朋友可以发现,在org.springframework.boot.actuate.endpoint.mvc 包下也有一系列的xxxEndpoint,这又是为什么呢? 原因是: 我们很多情况下,都是访问接口的方式获取应用的监控,之前的分析是其实现的底层,要想实现通过接口访问,还需要对其进行包装

【spring boot+mybatis】注解使用方式(无xml配置)设置自动驼峰明明转换(),IDEA中xxDao报错could not autowire的解决方法

最近使用spring boot+mybatis,使用IntelliJ IDEA开发,记录一些问题的解决方法. 1.在使用@Mapper注解方式代替XXmapper.xml配置文件,使用@Select等注解配置sql语句的情况下,如何配置数据库字段名到JavaBean实体类属性命的自动驼峰命名转换? 使用spring boot后,越来越喜欢用注解方式进行配置,代替xml配置文件方式.mybatis中也可以完全使用注解,避免使用xml方式配置mapper.(参考  springboot(六):如何优

spring boot 实战 / mvn spring-boot:run 参数详解

概述   Spring boot项目通常情况下有如下几种启动方式: 通过主类启动. 通过spring-boot的maven插件spring-boot-maven-plugin方式启动. 通过可执行jar/war包方式启动. 通过Servlet容器启动,如Tomcat.Jetty等.   今天我们来聊一下spring boot的maven插件spring-boot-maven-plugin启动过程中的profiles问题.首先,我们前往网站SPRING INITIALIZR,参照下图创建一个名称为