javascript
Spring表单的initBinder:绑定表单复杂属性
在查看SimpleFormController的API的時候,發現它有一個來自父類BaseCommandController的方法——initBinder:
BaseCommandController (Spring Framework)
initBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ExceptionThis method allows you to register custom editors for certain fields of your command class. For instance, you will be able to transform Date objects into a String pattern and back, in order to allow your JavaBeans to have Date properties and still be able to set and display them in an HTML interface.
Default implementation is empty.
回想以前學習IoC容器的時候,有提到“屬性編輯器”,只要在IoC配置文件里注冊特定“編輯器”,就可以將String轉換成javabean。
翻了翻書,想要自定義屬性編輯器,只要繼承PropertyEditorSupport,并重寫里面的setAsText方法,再進行注冊就行了。只不過書上是在IoC容器的配置文件注冊,而這里恐怕是通過重寫initBinder方法注冊。
initBinder有一個入參binder就是用來注冊屬性編輯器的,它是ServletRequestDataBinder類型,查看API,有一個來自父類DataBinder的方法——registerCustomEditor:
DataBinder (Spring Framework)public void registerCustomEditor(Class requiredType, String field, PropertyEditor propertyEditor)
If the property path denotes an array or Collection property, the editor will get applied either to the array/Collection itself (the PropertyEditor has to create an array or Collection value) or to each element (the PropertyEditor has to create the element type), depending on the specified required type.
Note: Only one single registered custom editor per property path is supported. In case of a Collection/array, do not register an editor for both the Collection/array and each element on the same property.
//自定義屬性編輯器
public class CollegeEditor extends PropertyEditorSupport{
??? private CollegeService collegeService;
??? public CollegeService getCollegeService() {
??? ??? return collegeService;
??? }
??? public void setCollegeService(CollegeService collegeService) {
??? ??? this.collegeService = collegeService;
??? }
????
??? public void setAsText(String collegeId){
??? ??? int id = Integer.valueOf(collegeId);
??? ??? College college = collegeService.findCollegeById(id);
??? ??? setValue(college);
??? }
}
//重寫SimpleFormController的initBinder方法
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder){
??? ??? binder.registerCustomEditor(College.class, "college", collegeEditor);
??? }
當然不要忘記IoC容器里該注入的要注入。
總結
以上是生活随笔為你收集整理的Spring表单的initBinder:绑定表单复杂属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软面试题目(一) 计算两个日期之间的天
- 下一篇: 基于libmad的MP3解码播放器