springMVC 前后台日期格式傳值解決方式之二(共二) @InitBinder的使用


關於springmvc日期問題的解決方式 除了本博客的【springMVC 前后台日期格式傳值解決方式之 @DateTimeFormat的使用和配置】一文,

還有如下這種方式:

在Controller里加上這段代碼:

 1     @InitBinder
 2     public void initBinder(ServletRequestDataBinder binder) {
 3         /**
 4          * 自動轉換日期類型的字段格式
 5          */
 6         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 7         binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
 8 
 9         
10     }

注意,如果前台有多重日期格式,寫成類似下面的方式是沒有什么卵用的

 1     @InitBinder
 2     public void initBinder(ServletRequestDataBinder binder) {
 3         /**
 4          * 自動轉換日期類型的字段格式
 5          */
 6         SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
 7         SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月");
 8         try {
 9             binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf2, true));
10         }catch(Exception e) {
11             binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf1, true));
12         }
13         
14     }

 

怎么解決呢?

可參考這個問題:http://bbs.csdn.net/topics/380055180

 

原文內容如下

----------------------------------------------------------分界線開始-----------------------------------------------------------

配置文件為

1
2
3
4
5
< bean  class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
     < property  name = "webBindingInitializer" >  
         < bean  class = "xx.xxx.MyBindingInitializer" />  
     </ property >  
</ bean



MyBindingInitializer中,initBinder方法里的
binder.registerCustomEditor(Date.class, new XXXEditor());


在XXXEditor的setAsText方法中,使用系統所有可能用到的format格式一一嘗試,捕獲異常,最后正確綁定。

-------------------------------------------------------分界線結束----------------------------------------------------------------

 

至於其中的XXXEditor怎么寫,大家可以參照例子中的CustomDateEditor,即:org.springframework.beans.propertyeditors.CustomDateEditor源碼中怎么寫的。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM