Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

关于SpringBoot中的Converter

关于Converter只能转换表单提交的数据,如果是以Json的方式提交就不能转化了请问整个源码怎么分析啊

这是我的Controller

    @PostMapping("/hello")
    public String hello( TestDtoWrapper dto) {
        return new Gson().toJson("666");
    }

这是我的POJO

    public static class TestDto {
        private String[] mids;

        public String[] getMids() {
            return mids;
        }

        public void setMids(String[] mids) {
            this.mids = mids;
        }
    }

    public static class TestDtoWrapper {
        private TestDto testDto;

        public TestDto getTestDto() {
            return testDto;
        }

        public void setTestDto(TestDto testDto) {
            this.testDto = testDto;
        }
    }

这是我的Converter

@Component
public class SpringToTestDtoCoverter implements Converter<String, HelloWorld.TestDto> {
    @Override
    public HelloWorld.TestDto convert(String source) {
        String[] split = source.split(",");
        HelloWorld.TestDto testDto=new HelloWorld.TestDto();
        testDto.setMids(split);
        return testDto;
    }
}

经测试,使用@RequestBody的方式接收参数,系统抛出无法转化的异常,使用表单提交数据则正常显示

希望大佬们可以告知~ 感谢!

参数上传成功转化
image.png

参数转化失败
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我自己debug了一下,粗浅解释一波,楼主搞清楚还请讲一讲。controller中参数上写RequestBody、RequestParam还有什么都不写的时候参数解析是不一样的,在使用requestbody的时候是通过反序列化json把json转换为java对象,你的json不能反序列化为你的参数,那么就会报错image.png
你参数上啥也没写 参数解析器使用的是
ModelAttributeMethodProcessor
这个解析器在解析参数的时候回去做参数绑定,这个过程会用到你定义的converter, 和requestbody不同的是他会去执行image.png
这个方法会调用你的converter ,这样你的字符串就能绑定到你的参数,但是仔细看requestbody解析的时候并没有执行这个。
希望对你有点帮助


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...