SpringMVC中利用@InitBinder來對頁面數據進行解析綁定


  同步發布:http://www.yuanrengu.com/index.php/springmvc-user-initbinder.html

  在使用SpingMVC框架的項目中,經常會遇到頁面某些數據類型是Date、Integer、Double等的數據要綁定到控制器的實體,或者控制器需要接受這些數據,如果這類數據類型不做處理的話將無法綁定。

      這里我們可以使用注解@InitBinder來解決這些問題,這樣SpingMVC在綁定表單之前,都會先注冊這些編輯器。一般會將這些方法些在BaseController中,需要進行這類轉換的控制器只需繼承BaseController即可。其實Spring提供了很多的實現類,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是夠用的。

       demo如下:

 

public class BaseController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new MyDateEditor()); binder.registerCustomEditor(Double.class, new DoubleEditor()); binder.registerCustomEditor(Integer.class, new IntegerEditor()); } private class MyDateEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(text); } catch (ParseException e) { format = new SimpleDateFormat("yyyy-MM-dd"); try { date = format.parse(text); } catch (ParseException e1) { } } setValue(date); } } public class DoubleEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Double.parseDouble(text)); } @Override public String getAsText() { return getValue().toString(); } } public class IntegerEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Integer.parseInt(text)); } @Override public String getAsText() { return getValue().toString(); } } }

 

 

 


免責聲明!

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



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