SpringMVC数据绑定

 

SpringMVC数据绑定

前言:由于请求中所带来的数据参数都是以key,value形式传递到controller,而传递过来的数据类型都是为String,当我们需要Integer,Date,Double等非String数据时,我们需要对其进行转换成需要的数据类型。

 

请求数据到controller过程:

 

1.绑定简单类型

      String---》Integer,Double,Float等数据类型,只要参数名字一致就可以绑定。

2.绑定简单的pojo类型

简单pojo类型只包括简单类型的属性。

绑定过程:request请求的参数名称和pojo的属性名一致,就可以绑定成功。

缺点:多个pojo拥有相同的属性名称。例,用户(user),员工(employee)都拥有name属性,在绑定的时候会导致无法绑定。

3.绑定包装的pojo类型

在页面的时候,指定所绑定的对象,例如user.name,employee.name

4.属性编辑器(propertyEditor)(了解)

SpringMVC没有支持全部的属性转换,所以需要我们自己自定义。

	//自定义属性编辑器
	@InitBinder
	public void initBinder(WebDataBinder binder) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(sdf, true));
	}

缺点:只能作用于当前页面,无法进行多个controller共用。

所以有了下面一种,

public class CustomPropertyEditor implements PropertyEditorRegistrar
{

    @Override
    public void registerCustomEditors(PropertyEditorRegistry binder) {
        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));

    }
}
<!-- 注册属性编辑器 -->
	<bean id="customPropertyEditor" class="cn.itcast.ssm.propertyeditor.CustomPropertyEditor"></bean> 
<!-- 自定义webBinder -->
	<bean id="customBinder"
		class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
		<property name="propertyEditorRegistrars">
			<list>
				<ref bean="customPropertyEditor"/>
			</list>
		</property>
	</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
	<property name="webBindingInitializer" ref="customBinder"></property> 
</bean>

5.转换器(converter)

定义一个转换器并注册,加入适配器中

public class CustomDateConverter implements Converter<String, Date>{

	@Override
	public Date convert(String source) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd").parse(source);
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}


}

springmvc.xml配置

	<mvc:annotation-driven conversion-service="conversionService" />

	 <!--转换器-->
    <!-- conversionService -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
            <bean class="conver.CustomDateConverter"/>
            </set>
        </property>
    </bean>

配好之后,Date类型的数据需要,就会自动转换了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值