SpringMVC數(shù)據(jù)綁定流程
SpringMVC主框架將ServletRequest對(duì)象及處理方法入?yún)?duì)象實(shí)例傳遞給DataBinder,DataBinder調(diào)用裝配在SpringMVC上下文中的ConversionService組件進(jìn)行數(shù)據(jù)類(lèi)型轉(zhuǎn)換,數(shù)據(jù)格式化的工作,將ServletRequest中的消息填充到入?yún)?duì)象中,然后再調(diào)用Validator組件對(duì)已綁定了請(qǐng)求消息數(shù)據(jù)的入?yún)?duì)象進(jìn)行數(shù)據(jù)合法性檢驗(yàn)叭披,并最終生成數(shù)據(jù)綁定結(jié)果BindingResult對(duì)象熏纯,BindingResult包含了已完成數(shù)據(jù)綁定的入?yún)?duì)象掐场,還包含相應(yīng)的校驗(yàn)錯(cuò)誤對(duì)象嚷堡。
自定義數(shù)據(jù)轉(zhuǎn)換
修改配置及核心類(lèi)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<context:component-scan base-package="converter"/>
<!-- 自定義參數(shù)綁定 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 轉(zhuǎn)換器 -->
<property name="converters">
<set>
<!-- StringToUser -->
<bean class="converter.StringToStudentConverter"/>
</set>
</property>
</bean>
</beans>
@Data
public class Student implements Serializable {
private static final long serialVersionUID = -3244941439014026595L;
private String name;
private String realName;
}
public class CustomDateConverter implements Converter<String,Date> {
public Date convert(String s) {
//實(shí)現(xiàn) 將日期串轉(zhuǎn)成日期類(lèi)型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//轉(zhuǎn)成直接返回
return simpleDateFormat.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果參數(shù)綁定失敗返回null
return null;
}
}
@Controller
public class StudentController {
@RequestMapping("/student")
public String save(@RequestParam("student") Student student) {
System.out.println(student);
return "success";
}
}
在瀏覽器輸入:http://localhost:8080/spring/student?student=wjk:snail
源碼走讀
從DispatcherServlet類(lèi)的doDispatch()調(diào)用handle開(kāi)始追代碼
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//AbstractNamedValueMethodArgumentResolver
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Class<?> paramType = parameter.getParameterType();
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
Object arg = resolveName(namedValueInfo.name, parameter, webRequest);
if (arg == null) {
if (namedValueInfo.defaultValue != null) {
arg = resolveDefaultValue(namedValueInfo.defaultValue);
}
else if (namedValueInfo.required) {
handleMissingValue(namedValueInfo.name, parameter);
}
arg = handleNullValue(namedValueInfo.name, arg, paramType);
}
else if ("".equals(arg) && (namedValueInfo.defaultValue != null)) {
arg = resolveDefaultValue(namedValueInfo.defaultValue);
}
//初始化DataBinder
if (binderFactory != null) {
WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
arg = binder.convertIfNecessary(arg, paramType, parameter);
}
handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);
return arg;
}
//DefaultDataBinderFactory
public final WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName)
throws Exception {
WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest);
if (this.initializer != null) {
this.initializer.initBinder(dataBinder, webRequest);
}
initBinder(dataBinder, webRequest);
return dataBinder;
}
//ConfigurableWebBindingInitializer
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
if (this.directFieldAccess) {
binder.initDirectFieldAccess();
}
if (this.messageCodesResolver != null) {
binder.setMessageCodesResolver(this.messageCodesResolver);
}
if (this.bindingErrorProcessor != null) {
binder.setBindingErrorProcessor(this.bindingErrorProcessor);
}
//綁定validator
if (this.validator != null && binder.getTarget() != null &&
this.validator.supports(binder.getTarget().getClass())) {
binder.setValidator(this.validator);
}
//綁定conversionService
if (this.conversionService != null) {
binder.setConversionService(this.conversionService);
}
if (this.propertyEditorRegistrars != null) {
for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
propertyEditorRegistrar.registerCustomEditors(binder);
}
}
}
接下來(lái)的代碼便是具體的轉(zhuǎn)化處理,有興趣可以自行閱讀。
@InitBinder裝配自定義編輯器
修改配置及核心類(lèi)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="conversion.way3"/>
</beans>
public class CustomStudentEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text.indexOf(":") > 0) {
Student user = new Student();
user.setName("wangjingkun");
setValue(user);
} else {
throw new IllegalArgumentException("dept param is error");
}
}
}
@Controller
public class StudentController {
//裝配自定義編輯器
@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Student.class,new CustomStudentEditor());
}
@RequestMapping("/student")
public String save(@RequestParam("student") Student student) {
System.out.println(student);
return "success";
}
}
@WebBindingInitializer裝配自定義編輯器
修改配置及核心類(lèi)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 注冊(cè)到適配器中 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="conversion.way2.MyBindingInitializer"></bean>
</property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="conversion.way2"/>
</beans>
public class MyBindingInitializer implements WebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(Student.class,new CustomStudentEditor());
}
}
@Controller
public class StudentController {
@RequestMapping("/student")
public String save(@RequestParam("student") Student student) {
System.out.println(student);
return "success";
}
}
如果對(duì)同一個(gè)類(lèi)型對(duì)象來(lái)說(shuō)同時(shí)裝配了自定義轉(zhuǎn)化器和自定義編輯器則優(yōu)先順序:
@InitBinder定義的編輯器優(yōu)先,其次conversionService定義的轉(zhuǎn)換器,最后是@WebBindingInitializer定義的編輯器。
Java原生的數(shù)據(jù)編輯器的不足
只支持字符串和Java對(duì)象之間的轉(zhuǎn)換,不支持兩個(gè)Java類(lèi)型之間的轉(zhuǎn)換。
對(duì)注解不明感,不能實(shí)施高級(jí)轉(zhuǎn)換邏輯。