软件编程
位置:首页>> 软件编程>> java编程>> SpringMVC 传日期参数到后台的实例讲解

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

作者:tianxia_09  发布时间:2022-01-18 23:31:48 

标签:SpringMVC,日期,参数,后台

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"/>

来源:http://www.cnblogs.com/tianxia-09/p/8032673.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com