溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

SpringMVC中如何利用@InitBinder來(lái)對(duì)頁(yè)面數(shù)據(jù)進(jìn)行解析綁定

發(fā)布時(shí)間:2021-06-17 14:52:16 來(lái)源:億速云 閱讀:170 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下SpringMVC中如何利用@InitBinder來(lái)對(duì)頁(yè)面數(shù)據(jù)進(jìn)行解析綁定,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

在使用SpingMVC框架的項(xiàng)目中,經(jīng)常會(huì)遇到頁(yè)面某些數(shù)據(jù)類(lèi)型是Date、Integer、Double等的數(shù)據(jù)要綁定到控制器的實(shí)體,或者控制器需要接受這些數(shù)據(jù),如果這類(lèi)數(shù)據(jù)類(lèi)型不做處理的話(huà)將無(wú)法綁定。

這里我們可以使用注解@InitBinder來(lái)解決這些問(wèn)題,這樣SpingMVC在綁定表單之前,都會(huì)先注冊(cè)這些編輯器。一般會(huì)將這些方法些在BaseController中,需要進(jìn)行這類(lèi)轉(zhuǎn)換的控制器只需繼承BaseController即可。其實(shí)Spring提供了很多的實(shí)現(xiàn)類(lèi),如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();  
    }  
  } 
}

以上是“SpringMVC中如何利用@InitBinder來(lái)對(duì)頁(yè)面數(shù)據(jù)進(jìn)行解析綁定”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI