将复杂对象如时间日期对应到实体对象的property中

本文介绍如何在Spring MVC中使用自定义PropertyEditor处理不同格式的日期数据。通过示例展示如何为特定字段注册CustomDateEditor,实现灵活的数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

众所周知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:

     

    1. @InitBinder  
    2. public void bindingPreparation(WebDataBinder binder) {  
    3.   DateFormat dateFormat1 = new SimpleDateFormat("d-MM-yyyy");  
    4.   CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat1, true);  
    5.   DateFormat dateFormat2 = new SimpleDateFormat("MMM d, YYYY");  
    6.   CustomDateEditor shipDateEditor = new CustomDateEditor(dateFormat2, true);  
    7.   binder.registerCustomEditor(Date.class, "orderDate", orderDateEditor);  
    8.   binder.registerCustomEditor(Date.class, "shipDate", shipDateEditor);  
    9. }  

     

     

    其实只要为每个变量绑定一个不同的Editor就可以了,对于不同的变量进行不同的处理。这样就能够方便的完成request 和 property 之间的binder了。


  • @InitBinder  
  • public void bindingPreparation(WebDataBinder binder) {  
  •   DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY");  
  •   CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true);  
  •   binder.registerCustomEditor(Date.class, orderDateEditor);  
  • }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值