SpringMVC自定義引數繫結實現詳解
阿新 • • 發佈:2020-01-07
一、概述
1.3 引數繫結過程
1.2 @RequestParam
如果request請求的引數名和controller方法的形引數名稱一致,介面卡自動進行引數繫結。如果不一致可以通過 @RequestParam 指定request請求的引數名繫結到哪個方法形參上。
對於必須要傳的引數,通過@RequestParam中屬性required設定為true,如果不傳此引數則報錯。
對於有些引數如果不傳入,還需要設定預設值,使用@RequestParam中屬性defaultvalue設定預設值。
可以繫結簡單型別:整型、字串、單精/雙精度、日期、布林型。
可以繫結簡單pojo型別
- 簡單pojo型別只包括簡單型別的屬性。
- 繫結過程:request請求的引數名稱和pojo的屬性名一致,就可以繫結成功。
問題:
- 如果controller方法形參中有多個pojo且pojo中有重複的屬性,使用簡單pojo繫結無法有針對性的繫結,
- 比如:方法形參有items和User,pojo同時存在name屬性,從http請求過程的name無法有針對性的繫結到items或user。
二、自定義繫結使用屬性編輯器
springmvc沒有提供預設的對日期型別的繫結,需要自定義日期型別的繫結。
2.1 使用WebDataBinder(瞭解)
在controller類中定義:
//自定義屬性編輯器 // @InitBinder // public void initBinder(WebDataBinder binder) throws Exception { // // Date.class必須是與controler方法形參pojo屬性一致的date型別,這裡是java.util.Date // binder.registerCustomEditor(Date.class,new CustomDateEditor( // new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true)); // }
使用這種方法問題是無法在多個controller共用。
2.2 使用WebBindingInitializer(瞭解)
使用WebBindingInitializer讓多個controller共用 屬性編輯器。
自定義WebBindingInitializer,注入到處理器介面卡中。
如果想多個controller需要共同註冊相同的屬性編輯器,可以實現PropertyEditorRegistrar介面,並注入webBindingInitializer中。
public class CustomPropertyEditor implements PropertyEditorRegistrar { @Override public void registerCustomEditors(PropertyEditorRegistry binder) { binder.registerCustomEditor(Date.class,new CustomDateEditor( new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true)); } }
配置如下:
<!-- 註冊屬性編輯器 --> <!-- 註冊屬性編輯器 --> <bean id="customPropertyEditor" class="com.hao.ssm.controller.propertyeditor.CustomPropertyEditor"></bean> <!-- 自定義webBinder --> <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="propertyEditorRegistrars"> <list> <ref bean="customPropertyEditor"/> </list> </property> </bean> <!--註解介面卡 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="webBindingInitializer" ref="customBinder"></property> </bean>
三、自定義引數繫結使用轉換器
3.1 實現Converter介面
定義日期型別轉換器和字串去除前後空格轉換器。
public class CustomDateConverter implements Converter<String,Date> { @Override public Date convert(String source) { try { //進行日期轉換 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source); } catch (Exception e) { e.printStackTrace(); } return null; } } public class StringTrimConverter implements Converter<String,String> { @Override public String convert(String source) { try { //去掉字串兩邊空格,如果去除後為空設定為null if(source!=null){ source = source.trim(); if(source.equals("")){ return null; } } } catch (Exception e) { e.printStackTrace(); } return source; } }
3.2 配置轉換器
<!-- 轉換器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.hao.ssm.controller.converter.CustomDateConverter" /> <bean class="com.hao.ssm.controller.converter.StringTrimConverter" /> </list> </property> </bean>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。