1、使用DateTimeFormat注解,在需要转换成Data格式的字段或者set方法上添加该注解,使用时可自动转换,注:每个要转换的字段都需要各自添加。注:需要在SpringMVC配置文件中设置注解驱动 <mvc:annotation-driven />用于自动装配需要的bean
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date gdate;
2、使用InitBinder注解和PropertiesEditor,在对应的controller中,添加由@InitBinder注解的方法,在客户端请求控制器方法时,每次都会调用该方法,如果有要转换的入参,则调用该方法内注册的自定义编辑器。
@InitBinder
public void initBinder(WebDataBinder binder){
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
binder.registerCustomEditor(Date.class,editor);
}
3、实现Converter接口并使用org.springframework.context.support.ConversionServiceFactoryBean或者org.springframework.format.support.FormattingConversionServiceFactoryBean注册到SpringMVC的配置文件中
定义Converter接口
package converter;
import org.springframework.core.convert.converter.Converter;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* @author: yinzhenying
* @date: 2020-02-22 20:57
* @desc:
*/
public class DateConvert implements Converter<String, Date> {
public Date convert(String text) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(text);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
对应的springmvc配置文件中增加
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converter.DateConvert"></bean>
</list>
</property>
</bean>
或者使用:
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converter.DateConvert"></bean>
</list>
</property>
</bean>