gpt4 book ai didi

java - 如何在Spring@RestController中映射多个bean?

转载 作者:太空宇宙 更新时间:2023-11-04 11:24:09 24 4
gpt4 key购买 nike

如何在 @RestController 中映射多个 bean

我正在使用 spring-web-4.3.8.RELEASE.jar

我尝试了一切:@RequestParam @RequestBody、@RequestAttribute、@RequestPart但没有任何效果...

package com.example.demo;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestService {

@RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Object[] demo(Foo foo, Bar bar) {
return new Object[]{foo, bar};
}

public static class Bar {
public Long id;
public String bar;
}

public static class Foo {
public Long id;
public String foo;
}
}

我的(编码的)有效负载是:

foo=%7B%22id%22%3A123%2C%22foo%22%3A%22foo1%22%7D&bar=%7B%22id%22%3A456%2C%22bar%22%3A%22bar1%22%7D

解码后的有效负载:

foo={"id":123,"foo":"foo1"}&bar={"id":456,"bar":"bar1"}

请求 header :

Content-Type: application/x-www-form-urlencoded

使用上面的代码,它返回:

[{"id":null,"foo":null},{"id":null,"bar":null}]

但我想要的是:

[{"id":123,"foo":"foo1"},{"id":456,"bar":"bar1"}]

谢谢

最佳答案

您正在 RestController 中创建静态内部类。 Spring 无法将收到的请求中的属性自动映射到所提到的 bean。请在单独的包或外部 Controller 中定义您的 bean。然后您就可以使用@RequestBody 来映射它。

            @RestController
public class RestService {

@RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Object[] demo(@RequestBody FooBar foobar) {
// your custom work
}
}


public class Bar {
public Long id;
public String bar;
}

public class Foo {
public Long id;
public String foo;
}

// created wrapper as @RequestBody can be used only with one argument.
public class FooBar {
private Foo foo;
private Bar bar;
}

引用请查看requestBody with multiple beans

还要确保请求参数名称与您的 bean 属性匹配。(即 Foo 和 Bar)。

关于java - 如何在Spring@RestController中映射多个bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com