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

相关推荐
java_logo43 分钟前
Jenkins Docker 容器化部署指南
java·运维·servlet·docker·容器·jdk·jenkins
♡喜欢做梦1 小时前
MyBatis操作数据库(进阶):动态SQL
java·数据库·sql·java-ee·mybatis
lusasky1 小时前
com.itextpdf堆外内存(Off-Heap Memory)泄露
java
.豆鲨包1 小时前
【Android】深入理解Window和WindowManager
android·java
Dylan的码园1 小时前
ArrayList与顺序表
java·数据结构·链表
Boop_wu1 小时前
[Java EE] 文件操作(系统文件和字节流字符流)
java·java-ee
Aevget1 小时前
「Java EE开发指南」如何在MyEclipse中开发EJB 2 Session Bean?(二)
java·ide·java-ee·开发工具·myeclipse
带刺的坐椅1 小时前
Solon AI 开发学习11 - chat - 工具调用与定制(Tool Call)
java·ai·llm·solon
sheji34161 小时前
【开题答辩全过程】以 基于JavaWeb的高校实验实训教学平台为例,包含答辩的问题和答案
java·spring boot