解决springboot 实体类String转Date类型的坑

目录
  • springboot 实体类String转Date类型
  • Date解析String类型的参数

springboot 实体类String转Date类型

前端传入一个String的时间字符串如:2019-07-18 23:59:59

后端实体类要在头顶加注解:

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

不然会出现报错

Date解析String类型的参数

1.首先建立String to Date 的解析实现

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";
    @Override
    public Date convert(String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        value = value.trim();
        try {
            if (value.contains("-")) {
                SimpleDateFormat formatter;
                if (value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                } else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }
                Date dtDate = formatter.parse(value);
                return dtDate;
            } else if (value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date failed", value));
        }
        throw new RuntimeException(String.format("parser %s to Date failed", value));
    }
}

2.创建全局的解析配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
@Configuration
public class DateHandlerAdapter {
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;
    /**
     * 增加字符串转日期的全局适配器
     */
    @PostConstruct
    public void initEditableAvlidation() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
                .getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService) initializer
                    .getConversionService();
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }
}

添加完这两个文件以后 在传参数类型为Date的参数时就不会再报 date解析失败的错误了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 关于Springboot日期时间格式化处理方式总结

    项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式. 注:本文基于Springboot2.x测试,如果无法生效可能是spring版本较低导致的.PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam.PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数是使用ModelAttributeMethodProcessor进行处理,而

  • spring boot @ResponseBody转换JSON 时 Date 类型处理方法【两种方法】

    spring boot @ResponseBody转换JSON 时 Date 类型处理方法[两种方法],Jackson和FastJson两种方式. spring boot @ResponseBody转换JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson和FastJson两种方式) 第一种方式:默认的json处理是 jackson 也就是对configureMessageConverters 没做配置时 mybatis数据查询返回的时间,是一串数字,如何转化成时间.

  • 基于springboot处理date参数过程解析

    这篇文章主要介绍了基于springboot处理date参数过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 前言 最近在后台开发中遇到了时间参数的坑,就单独把这个问题提出来找时间整理了一下: 正文 测试方法 bean代码: public class DateModelNoAnnotation { private Integer id; private Date receiveDate; } controller代码: @RestContr

  • 解决springboot 实体类String转Date类型的坑

    目录 springboot 实体类String转Date类型 Date解析String类型的参数 springboot 实体类String转Date类型 前端传入一个String的时间字符串如:2019-07-18 23:59:59 后端实体类要在头顶加注解: @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 不然会出现报错 Date解析String类型的参数 1.首先建立String to Date 的解析实现 import org.a

  • 浅谈Mybatis+mysql 存储Date类型的坑

    场景: 把一个时间字符串转成Date,存进Mysql.时间天数会比实际时间少1天,也可能是小时少了13-14小时 Mysql的时区是CST(使用语句:show VARIABLES LIKE '%time_zone%'; 查) 先放总结: 修改方法: 1. 修改数据库时区 2. 在jdbc.url里加后缀 &serverTimezone=GMT%2B8 3. 代码里设置时区,给SimpleDateFormat.setTimeZone(...) 例外:new Date() 可以直接存为正确时间,其他

  • Java实体类不要使用基本类型的知识点总结

    今天来记录一下,在项目中因为基本类型,所产生的bug 包装类:8种基本类型的包装类 应用场景:数据库建立实体映射多用包装类 这两句话是重点:就是建立实体类禁止使用基本数据量类型!!!而用对应的包装类, 为什么呢,看以下场景. JAVA代码 <font style="color:rgb(77, 77, 77)"><font face="&quot"><font style="font-size:16px">

  • 解决springboot 2.x 里面访问静态资源的坑

    目录 springboot 2.x 里面访问静态资源的坑 首先看一下 自动配置类的定义: 如果想要使用自动配置生效 SpringBoot2.x过后static下的静态资源无法访问 springboot 2.x 里面访问静态资源的坑 在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径 classpath:/META/resources/,classpath:/resources/,classpath:/static/,c

  • 解决SpringBoot 测试类无法自动注入@Autowired的问题

    原来的测试类的注解: @RunWith(SpringRunner.class) @SpringBootTest 一直没法自动注入,后来在@SpringBootTest, 加入启动类Application后就可以了 @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) 补充:spring boot项目单元测试时,@Autowired无法注入Service解决方式 首先确认: 测试类所在包名要和启动类一致

  • Springboot如何根据实体类生成数据库表

    目录 Springboot 实体类生成数据库表 第一步:添加springboot-data-jpa和数据库的依赖关系 第二步:编写yml文件的配置 第三步:实体类中使用的注解 第四步:启动项目是否生成表格 第五步:启动项目即可 springboot继承JPA根据实体类生成数据库中的表 1. pom中添加的依赖 2. application.yml中配置jpa配置 定义用户实体类,通过注解映射成数据库中的表 启动springboot项目 Springboot 实体类生成数据库表 JPA:sprin

  • mybaties plus实体类设置typeHandler不生效的解决

    目录 实体类设置typeHandler不生效问题 解决 mybaties中TypeHandler的使用 解决 实体类设置typeHandler不生效问题 实体类: @Data @TableName(value = "centre_manage_server_info") public class ServerEntity { @TableId(value = "id") //@Column(name = "id", isKey = true, i

  • 如何将Object类转换为实体类

    目录 将Object类转换为实体类 问题描述 问题原因 解决办法 实体类之间的相互转换 将Object类转换为实体类 问题描述 在用SpringBoot写controller的时候,需要接受一个map的Object,之后要把Object转为特定的类,代码如下: public boolean postArticle(@RequestBody Map<String, Object> map) {         ArticleInfo articleInfo = (ArticleInfo) map

  • IntelliJ IDEA下自动生成Hibernate映射文件以及实体类

    1.构建项目并添加项目结构配置以及配置初始参数 1.1.如图将基本的架子搭建好 1.2.点击File,弹出的菜单中点击Project Structure: 1.3.点击左侧的Modules,再点击"+"号,再在弹出的菜单中选择Hibernate: 1.4.在这时,项目中多出了一个Hibernate,点击Hibernate,再点击"+"号,选择hibernate.hbm.xml: 1.5.弹出的窗口中选择Hibernate的版本,然后点击OK: 1.6.点击OK后在原

  • Java如何实现实体类转Map、Map转实体类

    实体类转Map.Map转实体类 1.创建entity(User.java) package com.jeff.entity; public class User { private String userName; private String password; private Integer age; public User() { super(); } public User(String userName, String password, Integer age) { super();

随机推荐