1. 程式人生 > >SpringMVC中利用@InitBinder來對頁面資料進行解析繫結

SpringMVC中利用@InitBinder來對頁面資料進行解析繫結

在使用SpingMVC框架的專案中,經常會遇到頁面某些資料型別是Date、Integer、Double等的資料要繫結到控制器的實體,或者控制器需要接受這些資料,如果這類資料型別不做處理的話將無法繫結。

      解決方法:使用註解@InitBinder來解決這些問題,這樣SpingMVC在繫結表單之前,先註冊這些編輯器(@InitBinder)。一般會將這些方法些在utilController類中,需要進行這類轉換的控制器只需繼承utilController類即可。

utilController程式碼如下:

public class BaseController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
        binder.registerCustomEditor(Double.class, new DoubleEditor()); 
        binder.registerCustomEditor(Integer.class, new IntegerEditor());
    }

    private class DateEditor 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();    
        }    
    }  

}