27、SpringMvc项目页面传递时间字符串,而后台接口只接收Date类型数据的一种解决方案

解决方案:提供专门的类型转换器

定义转换器类

package com.haitai.oa.component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;

/**
 * 实现从前台传入的时间字符串自动转为Date对象
 * 
 * @author root
 *
 */
public class CostomDateConvert implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		if (source == null || source.isEmpty()) {
			return null;
		}
		// 定义支持的时间字符串格式
		SimpleDateFormat[] simpleDateFormats = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd HH:mm") };
		for (SimpleDateFormat simpleDateFormat : simpleDateFormats) {
			try {
				return simpleDateFormat.parse(source);
			} catch (ParseException e) {
				continue;
			}
		}
		return null;
	}

}

接下来就是对spring-mvc.xml(注:配置文件名可不同,本示例配置的该文件)进行配置,使其生效

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd              
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<mvc:default-servlet-handler />
	<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />

        <mvc:annotation-driven conversion-service="convertorService"></mvc:annotation-driven>
	
	<!-- 设置自定义的转换器 -->
	<bean id="convertorService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	    <property name="converters">
		<list>
			<bean class="com.haitai.oa.component.CostomDateConvert"></bean>
		</list>
	    </property>
	</bean>
</beans>

注:设置自定义的转换器 配置代码中,

        <bean class="com.haitai.oa.component.CostomDateConvert"></bean>  红色部分,需要根据自己实际情况填写

另外需要注意的地方,如下图红框标示

红框标示的两处地方必须一致,至此,重启项目后转换器就会默默工作了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值