1、注解方式,在controller層通過initBinder注解實現
1
2
3
4
5
6
|
@InitBinder public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)throws Exception { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); CustomDateEditor dateEditor = new CustomDateEditor(fmt, true); binder.registerCustomEditor(Date.class, dateEditor); } |
2、類型轉換,SpringMvc提供了Converter接口
1
2
3
4
5
6
7
8
9
10
11
12
|
public class DateConvert implements Converter< String , Date> { @Override public Date convert(String stringDate) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { return simpleDateFormat.parse(stringDate); } catch (ParseException e) { e.printStackTrace(); } return null; } } |
spring.xml中配置轉換器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!-- 第一步: 創建自定義日期轉換規則 --> < bean id = "dateConvert" class = "xxx.xxx.DateConvert" /> <!-- 第二步: 創建convertion-Service ,并注入dateConvert--> < bean id = "conversionService" class = "org.springframework.format.support.FormattingConversionServiceFactoryBean" > < property name = "converters" > < set > < ref bean = "dateConvert" /> </ set > </ property > </ bean > <!-- 第三步:注冊處理器映射器/處理器適配器 ,添加conversion-service屬性--> < mvc:annotation-driven conversion-service = "conversionService" /> |
以上這篇SpringMVC 傳日期參數到后臺的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/tianxia-09/p/8032673.html