your programing

이 RESTful 애플리케이션 예제에서 Spring @ResponseBody 주석은 어떻게 작동합니까?

lovepro 2020. 10. 4. 12:54
반응형

이 RESTful 애플리케이션 예제에서 Spring @ResponseBody 주석은 어떻게 작동합니까?


다음과 같은 방법으로 주석이 달린 메서드가 있습니다.

/**
* Provide a list of all accounts.
*/
//  TODO 02: Complete this method.  Add annotations to respond
//  to GET /accounts and return a List<Account> to be converted.
//  Save your work and restart the server.  You should get JSON results when accessing 
//  http://localhost:8080/rest-ws/app/accounts
@RequestMapping(value="/orders", method=RequestMethod.GET)
public @ResponseBody List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

그래서 저는이 주석으로 알고 있습니다.

@RequestMapping(value="/orders", method=RequestMethod.GET)

이 메서드 는 URL / orders로 표시되는 리소스에 대한 GET HTTP 요청을 처리 합니다 .

이 메서드는 List 를 반환하는 DAO 개체를 호출합니다 .

여기서 Account 는 시스템의 사용자를 나타내며 다음과 같이이 사용자를 나타내는 일부 필드가 있습니다.

public class Account {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long entityId;

    @Column(name = "NUMBER")
    private String number;

    @Column(name = "NAME")
    private String name;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name = "ACCOUNT_ID")
    private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();

    ...............................
    ...............................
    ...............................
}

내 질문은 : 주석 이 정확히 어떻게 @ResponseBody작동합니까?

반환 된 List<Account>객체 앞에 위치하므로이 목록을 참조한다고 생각합니다. 과정 문서에는이 주석이 다음과 같은 기능을 제공한다고 명시되어 있습니다.

결과가 HTTP 메시지 변환기 (MVC보기 대신)에 의해 HTTP 응답에 기록되는지 확인하십시오.

또한 공식 Spring 문서에서 읽기 : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html

그것은 List<Account>객체를 가져 와서 Http Response. 이것이 맞습니까 아니면 오해입니까?

이전 accountSummary()방법 의 주석에는 다음과 같은 내용 이 있습니다.

http : // localhost : 8080 / rest-ws / app / accounts에 액세스 할 때 JSON 결과를 받아야 합니다.

이것이 정확히 무엇을 의미합니까? 것을 그것은 뜻 List<Account>에 의해 반환 된 객체 accountSummary()메소드가 자동으로 변환되어 JSON포맷 한 다음에 넣어 Http Response? 또는 무엇을?

이 어설 션이 참이면 개체가 자동으로 JSON형식 으로 변환되도록 지정되어 있습니까? @ResponseBody주석이 사용될 때 표준 형식이 채택 됩니까 아니면 다른 곳에 지정되어 있습니까?


우선, 주석은 주석을 달지 않습니다 List. 마찬가지로 방법에 주석을 답니다 RequestMapping. 귀하의 코드는

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

이제 주석이 의미하는 것은 메서드의 반환 된 값이 HTTP 응답의 본문을 구성한다는 것입니다. 물론 HTTP 응답에는 Java 개체가 포함될 수 없습니다. 따라서이 계정 목록은 REST 애플리케이션에 적합한 형식 (일반적으로 JSON 또는 XML)으로 변환됩니다.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.


The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.


As mentioned by JB Nizet,

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

and

@RequestMapping(value="/orders", method=RequestMethod.GET)
public @ResponseBody List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

both are same. as @ResponseBody annotates the method not the list. @GMsoF -Installed message converters here can be used as follows.

@RequestMapping(value="/orders", method=RequestMethod.GET , produces={"application/json","application/xml"})
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Thanks :)


Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

참고URL : https://stackoverflow.com/questions/28646332/how-does-the-spring-responsebody-annotation-work-in-this-restful-application-ex

반응형