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 传日期参数到后台的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。