还是老规矩,开门见山。 我们开发的时候经常会从html,jsp中将参数传到后台,可是经常会遇到的一种情况就是传过来的数据到后台要组装成一种对象的格式,最常见的就是enum类型了。这时候spring提供的@initBinder这个annotation 就发挥了很大的作用。
众所周知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中文API文档 spring中文API文档 spring中文API文档 spring中文API文档
spring 源码解析
新版 spring 5 中文注释源码,关键源码位置都有中文注释,方便阅读源码 spring源码解读 Spring框架是由于软件开发的复杂性而创建的...从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。
spring源码 中英文注释
本篇文章主要介绍了Spring 中如何控制2个bean中的初始化顺序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Spring中文开发手册下载Spring中文开发手册下载Spring中文开发手册下载Spring中文开发手册下载
spring源码带注释的,直接可以阅读,不需要重新编译。
Spring中的方法注入方式.Spring中的方法注入方式.
6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...
Spring源代码解析(一):Spring中的事务处理 Spring源代码解析(二):ioc容器在Web容器中的启动 Spring源代码分析(三):Spring JDBC Spring源代码解析(四):Spring MVC Spring源代码解析(五):Spring AOP获取Proxy ...
Spring-5.0.0-官方中文文档 Spring-5.0.0-官方中文文档 Spring-5.0.0-官方中文文档
Spring中事务的传播属性详解,Spring中事务的传播属性详解
在非spring注解类中使用spring容器中的bean_普通类中使用yml配置文件中的配置信息,在大数据采集项目中用到的,已经测试过了
12.4.Spring.NET中的Advisor 12.5.使用ProxyFactoryObject创建AOP代理 12.5.1.基本原理 12.5.2.ProxyFactoryObject的属性 12.5.3.代理接口 12.5.4.代理一个类 12.6.使用ProxyFactory类以编程方式创建AOP代理 12.7....
NULL 博文链接:https://904353524-qq-com.iteye.com/blog/1774054
这个版本的帮助文档,修正了第一个版本中部分,连接打不开的问题。 Spring.net 是由Java 版的 Spring框架得来的,虽然说不是很流行,但是还是值行学习的。 软件格式:CHM
这是对Spring中注解是怎么实现的一个大概基本原理,条件是采取的理想状态,所以代码中还有缺陷的话请谅解,如果有需要的朋友可以放心下载,里面有详细的解释和流程。相信你能看懂
org.springframework.web.bind.WebDataBinder.class org.springframework.web.bind.annotation.InitBinder.class org.springframework.web.bind.annotation.ModelAttribute.class org.springframework.web.bind....
Spring 中文开发手册.pdf,Spring 中文开发手册.pdf