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对象

相关推荐
此剑之势丶愈斩愈烈1 天前
openssl 自建证书
java
面汤放盐1 天前
何时使用以及何时不应使用微服务:没有银弹
java·运维·云计算
0xDevNull1 天前
Spring Boot 自动装配:从原理到实践
java·spring boot·后端
qq_589568101 天前
java学习笔记,包括idea快捷键
java·ide·intellij-idea
Cry丶1 天前
架构师实战:Spring Authorization Server 落地企业级“无感” SSO(附设计映射与源码级接口剖析)
spring·spring security·oauth2.0·authorization·sso·无感登录
敖正炀1 天前
Spring 深度内核-核心容器与扩展机制-Spring 循环依赖终极剖析:三级缓存与 AOP 代理的纠缠
spring
小怪吴吴1 天前
idea 开发Android
android·java·intellij-idea
嘻嘻哈哈樱桃1 天前
牛客经典101题题解集--动态规划
java·数据结构·python·算法·职场和发展·动态规划
一次旅行1 天前
IDEA安装CC GUI新手指南
java·ide·intellij-idea
超梦dasgg1 天前
Spring AI 智能航空助手项目实战
java·人工智能·后端·spring·ai编程