SpringMVC数据绑定流程之数据转换

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原生的数据编辑器的不足

  1. 只支持字符串和Java对象之间的转换,不支持两个Java类型之间的转换。

  2. 对注解不明感,不能实施高级转换逻辑。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • 目录 前言 属性编辑器介绍 重要接口和类介绍 源码分析 编写自定义的属性编辑器 总结 参考资料 前言 Spring...
    yang2yang阅读 1,559评论 0 5
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,372评论 11 349
  • 温室里, 最寒冷的可是人心? 寒夜里, 最炙热的可是理想? 谁都可演成熟, 谁都可演沉默, 只有你的不羁在星空闪烁...
    蓝调易拉罐阅读 109评论 0 0
  • 多少人一旦迈出脚步 就再也不能回头 还怎么能在出走半生时候 归来时仍是天真少年 挫折苦痛经验 慢慢教会我们成长 初...
    植成乔木阅读 219评论 0 0