说说Spring中的WebDataBinder
2015-05-25 00:00
204 查看
还是老规矩,开门见山。 我们开发的时候经常会从html,jsp中将参数传到后台,可是经常会遇到的一种情况就是传过来的数据到后台要组装成一种对象的格式,最常见的就是enum类型了。这时候spring提供的@initBinder这个annotation 就发挥了很大的作用。
众所周知spring可以自动将request中的数据对应到对象的每个property,会自动的bind 一些simple data (Strings, int, float, etc.) 对应到 你所要求的Object中,可是如果面对复杂的对象,那就需要借助于PropertyEditor 来帮助你完成复杂对象的对应关系,这个借口提供了两个方法,将一个property 转成string getAsText(), 另外一个方法是将string类型的值转成property对应的类型。使用起来也很简单,来个例子:
这样同样面临一个问题,如果我有两个变量,变量名不一样,处理的规则也不一样,但是他们都是Date.class 类型, 这可怎么破。比如:
贴心的spring,提供了一种重载的方法。 for example:
其实只要为每个变量绑定一个不同的Editor就可以了,对于不同的变量进行不同的处理。这样就能够方便的完成request 和 property 之间的binder了。
以上的两个例子仅供抛砖引玉的作用,更多的spring内容还请大家自己不断探索,个人非常喜欢spring,也会不断发表新的spring文章。
众所周知spring可以自动将request中的数据对应到对象的每个property,会自动的bind 一些simple data (Strings, int, float, etc.) 对应到 你所要求的Object中,可是如果面对复杂的对象,那就需要借助于PropertyEditor 来帮助你完成复杂对象的对应关系,这个借口提供了两个方法,将一个property 转成string getAsText(), 另外一个方法是将string类型的值转成property对应的类型。使用起来也很简单,来个例子:
@InitBinder public void bindingPreparation(WebDataBinder binder) { DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY"); CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true); binder.registerCustomEditor(Date.class, orderDateEditor); }
这样同样面临一个问题,如果我有两个变量,变量名不一样,处理的规则也不一样,但是他们都是Date.class 类型, 这可怎么破。比如:
贴心的spring,提供了一种重载的方法。 for example:
@InitBinder public void bindingPreparation(WebDataBinder binder) { DateFormat dateFormat1 = new SimpleDateFormat("d-MM-yyyy"); CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat1, true); DateFormat dateFormat2 = new SimpleDateFormat("MMM d, YYYY"); CustomDateEditor shipDateEditor = new CustomDateEditor(dateFormat2, true); binder.registerCustomEditor(Date.class, "orderDate", orderDateEditor); binder.registerCustomEditor(Date.class, "shipDate", shipDateEditor); }
其实只要为每个变量绑定一个不同的Editor就可以了,对于不同的变量进行不同的处理。这样就能够方便的完成request 和 property 之间的binder了。
以上的两个例子仅供抛砖引玉的作用,更多的spring内容还请大家自己不断探索,个人非常喜欢spring,也会不断发表新的spring文章。
相关文章推荐
- 说说Spring中的WebDataBinder
- 说说Spring中的WebDataBinder
- 说说 spring-secuirty
- Spring 事务的隔离性,并说说每个隔离性的区别
- spring事务-说说Propagation及其实现原理(传播属性示例分析)
- Spring中的WebDataBinder
- 说说在Spring中如何引用外部属性文件的方法
- 简单说说spring的事务机制,以及是如何管理的?
- spring事务-说说Propagation及其实现原理
- 说说Spring中的WebDataBinder
- 说说个人对Struts,Spring,Hibernate分别是什么的理解
- 说说Spring中AOP和IOC的概念以及在spring中是如何应用的
- spring事务-说说Propagation及其实现原理
- 说说Spring Cloud版本的那些事儿。
- 来说说SpringMVC + JSONP的跨域请求
- 说说spring的自动装配
- 说说 Spring AOP 原理
- 说说你对Spring的理解
- Spring 事务的隔离性,并说说每个隔离性的区别,Spring 使用注解方式进行事务管理
- Java EE 5.0能取代Struts,Spring和Hibernate吗?