前台传时间参数错误
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createdDate';
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2017-01-05 12:45:32';
nested exception is java.lang.IllegalArgumentException
解决办法:
创建两个类
a.当发送时间类型时,直接用String发送
b.Feign客户端实现FeignFormatterRegistrar接口自定义DateFormatRegister
package com.haidai.Server.configuration;
import java.util.Date;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
/**
* @author wangdeqiu
* @date 2019年4月19日 上午11:43:17
* 类说明:时间处理
*/
public class DateFormatRegister implements FeignFormatterRegistrar{
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addConverter(Date.class, String.class, new Date2StringConverter());
}
private class Date2StringConverter implements Converter<Date,String>{
@Override
public String convert(Date source) {
if(source!=null) {
Long date = source.getTime();
return date.toString();
}else {
return null;
}
}
}
}
provider增加相应的解析器
package com.haidai.Server.configuration;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
/**
* @author wangdeqiu
* @date 2019年4月19日 上午11:59:11
* 类说明:请求前处理将字符串转成时间
*/
@Configuration
public class WebConfigBeans {
@Autowired private RequestMappingHandlerAdapter handlerAdapter;
@PostConstruct
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
genericConversionService.addConverter(String.class, Date.class, new String2DateConverter());
}
}
private class String2DateConverter implements Converter<String,Date>{
@Override
public Date convert(String source) {
if(StringUtils.isNotEmpty(source)) {
return new Date(Long.valueOf(source));
}else {
return null;
}
}
}
}
在启动类中处理时间为null的情况
//接收时间类型时传值不能为空的问题解决。
@InitBinder
public void initBinder(HttpServletRequest request
, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
在controller请求中增加参数,