Spring 的 RequestBody 和 ResponseBody 註解

REST,Spring MVC
Remote
0
10:59 AM · Dec 01 ,2025

1. 簡介

在本快速教程中,我們提供 Spring @RequestBody@ResponseBody 註解的簡潔概述。

2.

簡單來説,@RequestBody 註解將 HttpRequest 的請求體映射到傳輸或域對象,從而自動反序列化傳入的 HttpRequest 請求體到 Java 對象。

首先,讓我們來看一個 Spring 控制器方法:

@PostMapping("/request")
public ResponseEntity postController(
  @RequestBody LoginForm loginForm) {
 
    exampleService.fakeAuthenticate(loginForm);
    return ResponseEntity.ok(HttpStatus.OK);
}

Spring 自動將 JSON 反序列化為 Java 類型,假設指定了適當的類型。

默認情況下,帶有 @RequestBody 註解的類型必須與來自客户端控制器的 JSON 對應的類型:

public class LoginForm {
    private String username;
    private String password;
    // ...
}

在這裏,我們使用的一個對象來表示 HttpRequest 請求體映射到我們的 LoginForm 對象。

讓我們使用 CURL 測試它:

curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data 
  '{"username": "johnny", "password": "password"}' "https://localhost:8080/spring-boot-rest/post/request"

這就是 Spring REST API 和使用 @RequestBody 註解的 Angular 客户端所需要的全部內容。

3. @ResponseBody

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Suppose we have a custom Response object:

public class ResponseTransfer {
    private String text; 
    
    // standard getters/setters
}

Next, the associated controller can be implemented:

@Controller
@RequestMapping("/post")
public class ExamplePostController {

    @Autowired
    ExampleService exampleService;

    @PostMapping("/response")
    @ResponseBody
    public ResponseTransfer postResponseController(
      @RequestBody LoginForm loginForm) {
        return new ResponseTransfer("Thanks For Posting!!!");
     }
}

In the developer console of our browser or using a tool like Postman, we can see the following response:

{"text":"Thanks For Posting!!!"}

Remember, we don’t need to annotate the -annotated controllers with the @ResponseBody annotation

3.1. Setting the Content Type

When we use the @ResponseBody annotation, we’re still able to explicitly set the content type that our method returns.

For that, we can use the @RequestMapping‘s produces attribute. Note that annotations like @PostMapping, @GetMapping, etc. define aliases for that parameter.

Let’s now add a new endpoint that sends a JSON response:

@PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseTransfer postResponseJsonContent(
  @RequestBody LoginForm loginForm) {
    return new ResponseTransfer("JSON Content!");
}

In the example, we used the MediaType.APPLICATION_JSON_VALUE constant. Alternatively, we can use application/json directly.

Next, let’s implement a new method, mapped to the same /content path, but returning XML content instead:

@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseTransfer postResponseXmlContent(
  @RequestBody LoginForm loginForm) {
    return new ResponseTransfer("XML Content!");
}

Now, depending on the value of an Accept parameter sent in the request’s header, we’ll get different responses.

Let’s see this in action:

curl -i \ 
-H "Accept: application/json" \ 
-H "Content-Type:application/json" \ 
-X POST --data 
  '{"username": "johnny", "password": "password"}' "https://localhost:8080/spring-boot-rest/post/content"

The CURL command returns a JSON response:

HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 20 Feb 2020 19:43:06 GMT

{"text":"JSON Content!"}

Now, let’s change the Accept parameter:

curl -i \
-H "Accept: application/xml" \
-H "Content-Type:application/json" \
-X POST --data
  '{"username": "johnny", "password": "password"}' "https://localhost:8080/spring-boot-rest/post/content"

As anticipated, we get an XML content this time:

HTTP/1.1 200
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Thu, 20 Feb 2020 19:43:19 GMT

<ResponseTransfer><text>XML Content!</text></ResponseTransfer>

4. 結論

我們為 Spring 應用構建了一個簡單的 Angular 客户端,演示瞭如何使用 @RequestBody@ResponseBody 註解。

此外,我們還展示瞭如何設置內容類型,使用 @ResponseBody

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.