zoukankan      html  css  js  c++  java
  • SpringMVC解决@ResponseBody返回Json的Date日期类型的转换问题

    在做项目的时候,发现后台把Date类型的属性以json字符串的形式返回,前台拿不到转换后的日期格式,始终响应回去的都是long类型时间戳。

    查阅资料之后找到解决方法:

    方法一(在springmvc的xml配置文件下):

    <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                            <property name="dateFormat">
                                <bean class="java.text.SimpleDateFormat">
                                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd" />
                                </bean>
                            </property>
                        </bean>
                    </property>
                </bean>
     
            </mvc:message-converters>
     
        </mvc:annotation-driven>

    方法二(依赖jackson包):

    第一步:依赖jar包

    <!-- jackson-databind -->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
    </dependency>


    第二步:在实体字段上添加注解(@JsonFormat)

    修改之后运行结果:


    还有就是前端提交日期的json,格式为2018-07-26,日期字段希望能自动填充到后台controller方法的Date对象里。经过查阅资料,解决方法就是:

    public class Book {
        private String id;
        private String bname;
        private double price;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date pressDate;
        private String author;
    }

    Date日期字段加入注解 @DateTimeFormat(pattern = "yyyy-MM-dd")

    参考:https://www.cnblogs.com/MrSaver/p/6498626.html

  • 相关阅读:
    SpringBoot结合ShardingSphere实现分库分表、读写分离
    SpringBoot结合ShardingSphere实现主从读写分离
    使用Sentinel实现Spring Cloud Gateway网关流量控制
    使用Sentinel实现热点参数限流
    对比学习UIKit和AppKit--入门级
    UIViewController
    C++的异常处理之一:throw是个一无是处的东西
    About Closure
    理解Objective C 中id
    关于文件压缩的一些小知识
  • 原文地址:https://www.cnblogs.com/hhmm99/p/9960887.html
Copyright © 2011-2022 走看看