1. 程式人生 > >SpringMVC中繫結日期型別的幾種方式總結

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>