当前位置:首页 > java > 正文内容

SpringBoot http请求 提交日期参数 转换失败的解决方法 (无法自动转换字符串到日期)

关中浪子4年前 (2021-11-08)java1703
买泛域名SSL证书 送5斤装现摘猕猴桃一箱、同时提供技开源商城搭建免费技术支持。
泛域名ssl证书 239元1年送1个月、单域名39元1年,Sectigo(原Comodo证书)全球可信证书,强大的兼容性,高度安全性,如有问题7天内可退、可开发票
加微信VX 18718058521 备注SSL证书
【腾讯云】2核2G4M云服务器新老同享99元/年,续费同价

如果你有类似如下报错信息,可阅读此文尝试解决:


2018-08-18 14:05:17.687  WARN 17100 --- [p-nio-80-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 4 errors
Field error in object 'sysUserDO' on field 'userBecomeTime': rejected value []; codes [typeMismatch.sysUserDO.userBecomeTime,typeMismatch.userBecomeTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userBecomeTime,userBecomeTime]; arguments []; default message [userBecomeTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userBecomeTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userBirthday': rejected value []; codes [typeMismatch.sysUserDO.userBirthday,typeMismatch.userBirthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userBirthday,userBirthday]; arguments []; default message [userBirthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userBirthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userDimissionTime': rejected value []; codes [typeMismatch.sysUserDO.userDimissionTime,typeMismatch.userDimissionTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userDimissionTime,userDimissionTime]; arguments []; default message [userDimissionTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userDimissionTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userJoinTime': rejected value []; codes [typeMismatch.sysUserDO.userJoinTime,typeMismatch.userJoinTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userJoinTime,userJoinTime]; arguments []; default message [userJoinTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userJoinTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]

前台像后台传递参数带日期是,springboot自动绑定会失败


比如:


前台代码:



后台接收代码:



报错信息:



 


 


下面给出解决方法:


1.创建一个class 名称:StringToDateConverter  稍后会用到此类


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";
private static final String dateFormat2 = "yyyy/MM/dd HH:mm:ss";
private static final String shortDateFormat2 = "yyyy/MM/dd";
 
@Override
public Date convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
source = source.trim();
try {
SimpleDateFormat formatter;
if (source.contains("-")) {
if (source.contains(":")) {
formatter = new SimpleDateFormat(dateFormat);
} else {
formatter = new SimpleDateFormat(shortDateFormat);
}
Date dtDate = formatter.parse(source);
return dtDate;
} else if (source.contains("/")) {
if (source.contains(":")) {
formatter = new SimpleDateFormat(dateFormat2);
} else {
formatter = new SimpleDateFormat(shortDateFormat2);
}
Date dtDate = formatter.parse(source);
return dtDate;
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date fail", source));
}
 
throw new RuntimeException(String.format("parser %s to Date fail", source));
 
}
}

其中StringUtils为apache lang3包,可以自己手写替代,或导包


<!--apache lang3-->

<dependency>

   <groupId>org.apache.commons</groupId>

   <artifactId>commons-lang3</artifactId>

   <version>3.1</version>

</dependency>

2.添加配置类,把我们写的处理日期的类交给spring,让它知道怎么处理


 

import com.here.hulk.utils.StringToDateConverter;

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 WebAppConfig {

@Autowired

private RequestMappingHandlerAdapter handlerAdapter;

 

 

/**

* 此方法解决前台提交的日期参数绑定不正确问题,将自己实现的StringToDateConverter交给spring,让其知道如何进行处理

*/

@PostConstruct //@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
genericConversionService.addConverter(new StringToDateConverter());
}
}
}

3.重启测试,有问题继续想办法,总是能解决的


 


找梯子最重要的就是稳定,这个已经上线三年了,一直稳定没有被封过,赶紧下载备用吧!

扫描二维码推送至手机访问。

版权声明:本文由码农翻生发布,如需转载请注明出处。

本文链接:https://lubojian.cn/post/55.html

分享给朋友:

相关文章

springmvc学习返回视图或字符串

springmvc学习返回视图或字符串

返回试图1:直接返回String字符串,拼接前后缀,进行页面跳:2:返回modelAndView,拼接前后缀,返回页面success.jsp3:注入modelAndView,拼接前后缀返回页面success.jsp4:把model与view...

poi4.0.0读取excel文件时报java.lang.NoClassDefFoundError: org/apache/commons/compress/archivers/zip/ZipFile

最近想用poi写个处理excel的工具,看了一下poi的官网,出了个4.0.0的版本,于是想尝尝鲜,下载了一把poi4.0.0的bin。下载的是下面的文件: 下载完,将压缩包里所有的jar包导入到工程中(当然,如果只需要处理exc...

POI实现 Excel 导入导出

一、代码1-1、导入依赖<dependency>       <groupId>org.apache.poi</groupId>  ...

Maven下载、安装、环境变量配置教程【图文】详细教程

Maven下载、安装、环境变量配置教程【图文】详细教程

一、下载1、直接去官网下载即可,很轻量级大小就十来兆官方下载页面地址:http://maven.apache.org/download.cgi2、进去官网之后,就可以直接下载,提示:jdk1.8支持所有版本的Maven,所以不用担心兼容问题...

简单两步配置 Maven远程仓库 阿里云镜像 【图文】

简单两步配置 Maven远程仓库 阿里云镜像 【图文】

为什么配置阿里云的镜像,是因为它比较快。咱国内的,赞1、打开Maven目录中conf目录下找打setting.xml右键打开;2、添加这段到mirrors标签中,默认这标签是没有什么内容的;<!-- 阿里云镜像 --> ...

静态代理和动态代理的区别

静态代理静态代理,设计模式的代理模式举例通常是用这种方式实现的,对于每一个要代理的类为了添加相同的操作,需要分别去实现其接口,容易造成代理类过多public interface Subject {  ...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。