SpringMVC数据绑定流程
SpringMVC主框架将ServletRequest对象及处理方法入参对象实例传递给DataBinder,DataBinder调用装配在SpringMVC上下文中的ConversionService组件进行数据类型转换,数据格式化的工作,将ServletRequest中的消息填充到入参对象中,然后再调用Validator组件对已绑定了请求消息数据的入参对象进行数据合法性检验,并最终生成数据绑定结果BindingResult对象,BindingResult包含了已完成数据绑定的入参对象,还包含相应的校验错误对象。
自定义数据转换
修改配置及核心类
<?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"/>
<!-- 自定义参数绑定 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<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) {
//实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//转成直接返回
return simpleDateFormat.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果参数绑定失败返回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类的doDispatch()调用handle开始追代码
// 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);
}
}
}
接下来的代码便是具体的转化处理,有兴趣可以自行阅读。
@InitBinder装配自定义编辑器
修改配置及核心类
<?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装配自定义编辑器
修改配置及核心类
<?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">
<!-- 注册到适配器中 -->
<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";
}
}
如果对同一个类型对象来说同时装配了自定义转化器和自定义编辑器则优先顺序:
@InitBinder定义的编辑器优先,其次conversionService定义的转换器,最后是@WebBindingInitializer定义的编辑器。
Java原生的数据编辑器的不足
只支持字符串和Java对象之间的转换,不支持两个Java类型之间的转换。
对注解不明感,不能实施高级转换逻辑。