如果从数据库获取类型为Date日期的字段显示到前台的时候出现报400的问题就可以看看了
一、使用注解方式解决前端日期在后台转换报错的问题。
1、新建日期转化类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
@Configuration
public class AppConfig {
@Bean
public FormattingConversionService conversionService() {
// Use the DefaultFormattingConversionService but do not register defaults
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);
// Ensure @NumberFormat is still supported
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
// Register date conversion with a specific global format
DateFormatterRegistrar registrar = new DateFormatterRegistrar();
registrar.setFormatter(new DateFormatter("yyyy-MM-dd"));
registrar.registerFormatters(conversionService);
return conversionService;
}
}
2、springmvc.xml中配置mvc注解驱动中增加如下内容
<mvc:annotation-driven conversion-service="conversionService"/>
二、使用xml方式解决前端日期在后台转换报错的问题。
1、创建日期转换类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
- 日期格式转化
- @author shy
*/
public class DateConvert implements Converter<String,Date>{
private String datePatten;
public void setDatePatten(String datePatten) {
this.datePatten = datePatten;
}
@Override
public Date convert(String date) {
if(date==null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(this.datePatten);
try {
Date d = sdf.parse(date);
return d;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
2、springmvc.xml中配置mvc注解驱动中增加如下内容
<mvc:annotation-driven conversion-service="conversionService"/>
3、springmvc.xml中增加如下bean
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.hp.util.DateConvert">
<property name="datePatten" value="yyyy-MM-dd"></property>
</bean>
</list>
</property>