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

标签 java spring spring-mvc

如何在 @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/

相关文章:

java - JLabel : 的对齐问题

java - 将 Spring Security 添加到 Gradle 项目会破坏 Spring Data JPA?

mysql - 直接从登陆页面单击“忘记密码”时出现错误“找不到网址”

java - BeanNotOfRequiredTypeException 与 Spring AOP

java.lang.AssertionError : Status expected:<200> but was:<405> 错误

java - 如何计算 ListView 中勾选的复选框的数量

java - 我是安卓开发新手。我有个问题

java - Spring Web - 类级 RequestMapping 不起作用

java - Spring MVC - 当休息 Controller 响应类型为空时自动返回 204

java - 将 int[] 转换为 char[] 无法正常工作