Java Spring MVC @ResponseBody 返回一个列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20515607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:28:36  来源:igfitidea点击:

Spring MVC @ResponseBody return a List

javaspringweb-services

提问by MychaL

We would like to create a "WebService" which return a list of specific objects. And we would like to call this webservice from another java program by apache http clients library.

我们想创建一个返回特定对象列表的“WebService”。我们想通过 apache http 客户端库从另一个 java 程序调用这个 web 服务。

At this moment, if we call the webservice from Firefox, an 406 error page appears.

此时,如果我们从 Firefox 调用 webservice,则会出现 406 错误页面。

Do we have to use JSON or XML to transfert the list ? How to do that, and how to get the list with apache http clients ?

我们是否必须使用 JSON 或 XML 来传输列表?如何做到这一点,以及如何使用 apache http 客户端获取列表?

Thank you.

谢谢你。



[EDIT]

[编辑]

The only thing which is working is to create some entities with JAXB annotations in order to serialize into XML.

唯一有效的是使用 JAXB 注释创建一些实体,以便序列化为 XML。

@XmlRootElement(name = "person")
public class Person {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

@XmlRootElement(name = "persons")
public class PersonList {

    @XmlElement(required = true)
    public List<Person> persons;

    public List<Person> getData() {
        return persons;
    }

    public void setData(List<Person> persons) {
        this.persons = persons;
    }

}

@RequestMapping(value = "/hello.html", method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public ResponseEntity<PersonList> hello() {
    PersonList test = new PersonList();

    List<Person> rep = new ArrayList<Person>();
    Person person1 = new Person();
    person1.setId("1");
    Person person2 = new Person();
    person2.setId("2");

    rep.add(person1);
    rep.add(person2);

    test.setData(rep);
    // return test;

    HttpHeaders responseHeaders = new HttpHeaders();
    List<MediaType> medias = new ArrayList<MediaType>();
    medias.add(MediaType.ALL);
    responseHeaders.setAccept(medias);
    return new ResponseEntity<PersonList>(test, responseHeaders, HttpStatus.OK);
}

I tried with produces and to return directly the object but still error 406. XML + ResponseEntity works.

我尝试使用生产并直接返回对象,但仍然出现错误 406。XML + ResponseEntity 有效。

It is very strange cause i saw an exemple very simple where the object is converted into json and appears into web browser.

这很奇怪,因为我看到了一个非常简单的例子,其中对象被转换为 json 并出现在 Web 浏览器中。

So, now i have to understand how to get the response and to convert XML into entities...

所以,现在我必须了解如何获得响应并将 XML 转换为实体......

采纳答案by MychaL

During 2 days, i tried many ways : - responseEntity - httpheaders - XML etc...

在 2 天里,我尝试了很多方法:- responseEntity - httpheaders - XML 等...

For a JSON (default behavior), the project need a library with all Spring library. Here the library to declare in Maven project.

对于 JSON(默认行为),项目需要一个包含所有 Spring 库的库。这里是要在 Maven 项目中声明的库。

<dependency>
    <groupId>org.codehaus.Hymanson</groupId>
    <artifactId>Hymanson-mapper-asl</artifactId>
    <version>1.7.1</version>
</dependency> 

Without this library, i have an Error (406).

没有这个库,我有一个错误(406)。

Thank you anyway for all your answers & advices.

无论如何,感谢您的所有回答和建议。

回答by Jeevan Patil

You can build REST services using spring mvc framework. It will return JSON / XML. And call those services using HTTP clients / rest templates and use returned JSON to display information.

您可以使用 spring mvc 框架构建 REST 服务。它将返回 JSON/XML。并使用 HTTP 客户端/休息模板调用这些服务并使用返回的 JSON 来显示信息。

Spring controllers can return an object, list of objects as well. And some mappings (Hymanson and JAXB) will allow it to convert object into JSON / XML.

Spring 控制器也可以返回一个对象,对象列表。并且一些映射(Hymanson 和 JAXB)将允许它将对象转换为 JSON/XML。

If your services accept request data, you can send an object to service and get response data.

如果您的服务接受请求数据,您可以向服务发送一个对象并获得响应数据。

You can use Grails frameworks as well.

您也可以使用 Grails 框架。

回答by Rytis Alekna

Yes, when your controller method in annotated with @ResponseBody, Spring transforms returned data into JSON.

是的,当您的控制器方法用 注释时@ResponseBody,Spring 会将返回的数据转换为JSON

回答by Tim B

@ResponseBody will automatically encode the object you return to appropriate formats based on the Accept header of the request and the presence of JSON and/or XML libraries in the classpath.

@ResponseBody 将根据请求的 Accept 标头以及类路径中是否存在 JSON 和/或 XML 库,自动将您返回的对象编码为适当的格式。

It can be easier/safer to define your own object to wrap the list in though rather than returning the list directly - as that gives you more control over the encoding and also allows you to potentially add other data in the future.

定义您自己的对象来包装列表会更容易/更安全,而不是直接返回列表 - 因为这可以让您更好地控制编码,并且还允许您在未来添加其他数据。

回答by Michael-O

You should rather use ResponseEntityfor that. @ResponseBodygives you absolutely no control over the response.

你应该使用ResponseEntity它。@ResponseBody让您完全无法控制响应。

回答by Manjush

The @ResponseBodyannotation tells Spring that we will be returning data in the response body rather than rendering a JSP.

@ResponseBody注解告诉 Spring 我们将在响应正文中返回数据而不是呈现 JSP。

When the @ResponseBodyannotation is used, Spring will return the data in a format that is acceptable to the client. That is, if the client request has a header to accept json and Hymanson-Mapper is present in the classpath, then Spring will try to serialize the return value to JSON. If the request header indicates XML as acceptable (accept=application/xml) and Jaxb is in the classpath and the return type is annotated with Jaxb annotation, Spring will try to marshall the return value to XML.

当使用@ResponseBody注解时,Spring 会以客户端可接受的格式返回数据。也就是说,如果客户端请求有一个头来接受 json 并且类路径中存在 Hymanson-Mapper,那么 Spring 将尝试将返回值序列化为 JSON。如果请求头指示 XML 为可接受 ( accept=application/xml) 并且 Jaxb 在类路径中并且返回类型使用 Jaxb 注释进行注释,Spring 将尝试将返回值编组到 XML。

回答by Yasir Shabbir Choudhary

Actually you have to use REST web service that carry JSON/XML format as Objects representation. I prefer JSON because this is very light weight.

实际上,您必须使用携带 JSON/XML 格式作为对象表示的 REST Web 服务。我更喜欢 JSON,因为它的重量很轻。

First you need to add dependency in your Pom.xml

首先你需要在你的 Pom.xml 中添加依赖

<dependency>
<groupId>org.codehaus.Hymanson</groupId>
<artifactId>Hymanson-mapper-asl</artifactId>
<version>1.7.1</version>

and your method handler is here

你的方法处理程序在这里

    @ResponseBody
    @RequestMapping(value = "/your URL")
    public ArrayList<Long> getInboxPage(@RequestParam int var,HttpSession session) {

        ArrayList<Long> fooList=new ArrayList<Long>();
        fooList.add(1L);
        fooList.add(2L);
        fooList.add(3L);

        return fooList;

    }

NOTE: Spring automatically make JSON if you write @ResponseBody annotation in your method handler you don't need to add Hymanson dependency in your pom.xml file.

注意:如果您在方法处理程序中编写 @ResponseBody 注释,Spring 会自动生成 JSON,您不需要在 pom.xml 文件中添加 Hymanson 依赖项。