SpringMVC中利用@InitBinder來對頁面資料進行解析綁定,springmvcinitbinder

來源:互聯網
上載者:User

SpringMVC中利用@InitBinder來對頁面資料進行解析綁定,springmvcinitbinder

  同步發布: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();            }        }  }

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.