SpringMVC中绑定日期类型的几种方式总结

1,在bean实体中使用@DateTimeFormat(pattern="yyyy-MM-dd")


2,自定义一个全局类型转换器

package com.itpengwei.bos.converters;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.converter.Converter;

/**
 * S:需要转换的资源 T:target目标资源
 * 
 * @author pengwei
 *
 */
public class GloabDateConverters implements Converter<String, Date> {
	
	@Override
	public Date convert(String source) {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date target = dateFormat.parse(source);
			// 转换完成返回出去
			return target;
		} catch (Exception e) {
			e.printStackTrace();
			// 转换异常,返回null
			return null;
		}
	}

}

然后在springmvc.xml中配置自定义类型转换器

<mvc:annotation-driven
		conversion-service="converService" />
	<!-- 配置转换器工厂 -->
	<bean id="converService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<list>
				<!-- 配置自定义日期转换器 -->
				<bean class="com.itpengwei.bos.converters.GloabDateConverters" />
			</list>
		</property>
	</bean>

猜你喜欢

转载自blog.csdn.net/pw191410147/article/details/80674569