首页 > 开发 > Java > 正文

SpringMVC 传日期参数到后台的实例讲解

2024-07-13 10:14:35
字体:
来源:转载
供稿:网友

1、注解方式,在controller层通过initBinder注解实现

@InitBinderpublic 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 传日期参数到后台的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持VeVb武林网。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表