解决从数据库获取类型为Date日期的字段显示到前台的时候出现报400

如果从数据库获取类型为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>

亲测这两种方式都可以解决日期转换报错的问题

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值