SpringMVC 传日期参数到后台的实例讲解
发布时间:2020-12-14 20:19:45 所属栏目:Java 来源:网络整理
导读:1、注解方式,在controller层通过initBinder注解实现 @InitBinderpublic void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)throws Exception { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); CustomDateEditor dateEdi
1、注解方式,在controller层通过initBinder注解实现 @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接口 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中配置转换器 <!-- 第一步: 创建自定义日期转换规则 --> <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 传日期参数到后台的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |