spring mvc 自定义Converter 设置

我们在开发过程中,前端页面传过来的参数类型并都不是后端所期待的,前端传递过来的参数我们后端不能处理就会报错

前端传递过来的是字符串,返回后端报错

因为spring MVC并不知道怎么将 "玳瑁,1" 转换成他理解的样子

java 复制代码
public class Pet {
    private String name;
    private int age;
    private int sex; //1:男,2:女
    private Double weight;
}

这个时候我们需要一个自定义 configure

java 复制代码
@Configuration //告诉boot 这是一个配置类 == 配置文件,在 Spring 容器中默认是单实例
public class MyConfig {

    //配置类里面使用@Bean标注在方法上给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值就是组件在容器中的实例,默认是单实例
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, Pet>() {

                    @Override
                    public Pet convert(String source) {
                        if (StringUtils.isEmpty(source)) {
                            return null;
                        }
                        Pet pet = new Pet();
                        String[] split = source.split(",");
                        pet.setName(split[0]);
                        pet.setAge(Integer.valueOf(split[1]));
                        return pet;
                    }
                });
            }
        };
    }
}

我们点进 WebMvcConfigurer 发现这是一个接口,在这个接口中有一个方法 addFormatters(FormatterRegistry registry) 。添加类型转换器和格式化器。

debug重启项目,我们来到 ModelAttributeMethodProcessor类的WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);方法中
(WebDataBinder:外部数据绑定器,将请求参数绑定到指定的javabean里面,指定的javaBean就是之前创建的 attribute)

此时我们发现外部数据绑定器数量由原来的124个变成125个

我们放行代码,来到我们自定义的 converter 中,自定义的converter会将前端传过来的字符串"玳瑁,1"分割,并赋值给pet对象

相关推荐
蒸蒸yyyyzwd1 天前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
程序员徐师兄1 天前
Windows JDK11 下载安装教程,适合新手
java·windows·jdk11 下载安装·jdk11 下载教程
RANCE_atttackkk1 天前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
五岳1 天前
DTS按业务场景批量迁移阿里云MySQL表实战(下):迁移管理平台设计与实现
java·应用·dts
zhougl9961 天前
Java 所有关键字及规范分类
java·开发语言
Python 老手1 天前
Python while 循环 极简核心讲解
java·python·算法
java1234_小锋1 天前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
Mr_Xuhhh1 天前
MySQL函数详解:日期、字符串、数学及其他常用函数
java·数据库·sql
测试开发Kevin1 天前
小tip:换行符CRLF 和 LF 的区别以及二者在实际项目中的影响
java·开发语言·python
笨手笨脚の1 天前
Redis: Thread limit exceeded replacing blocked worker
java·redis·forkjoin·thread limit