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 天前
Mac安装多版本jdk(jenv)
java·开发语言·macos
计算机安禾1 天前
【c++面向对象编程】第32篇:移动语义与右值引用:现代C++性能优化核心
java·c++·性能优化
JAVA面经实录9171 天前
JVM高频面试总结(背诵完整版)
java·开发语言·jvm
ChoSeitaku1 天前
11.异常_throws_try...catch_BigInteger_BigDecimal_Date_Calendar_LocalDate_Integer
java
胡志辉的博客1 天前
完全开源、本地 SQLite 管理一切:我写了一个桌面邮件客户端 OneMail
java·sqlite·开源
沪漂阿龙1 天前
Java JVM 面试题详解:JVM运行原理、内存模型、堆栈方法区、GC垃圾回收、JIT编译、类加载机制与线上调优全攻略
java·开发语言·jvm
小碗羊肉1 天前
Maven高级
java·开发语言·maven
星秀日1 天前
Spring Boot + Sa-Token 实时聊天系统:用户注册流程源码深度剖析
java·人工智能·spring·状态模式
YOU OU1 天前
SpringBoot 配置文件
java·spring boot·后端
c++之路1 天前
观察者模式(Observer Pattern)
java·网络·观察者模式