多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Spring 中的`RequestBody`注解 > 原文: [https://javatutorial.net/requestbody-annotation-in-spring](https://javatutorial.net/requestbody-annotation-in-spring) `@RequestBody`注解可用于处理 Web 请求。 ![java-featured-image](https://img.kancloud.cn/05/3e/053ee0bb59842d92359246c98f815e0c_780x330.jpg) 更具体地说,它用于将方法参数与请求的主体绑定,其工作方式是`HttpMessageConverter`根据请求内容的类型转换请求的主体。 ### 语法 ```java <modifier> <return-type> <method-name> (@RequestBody <type> <name>) { } ``` 以上语法的示例: ```java public String congratulateEmployee(@RequestBody Employee emp) { } ``` 包含上述方法的完整`Controller`类: ```java @RestController public class CongratulationsController { @PostMapping("/congratulations") public Manager assignToManager(@RequestBody Employee emp) { String name = emp.getName(); int yearsWorked = emp.getYearsWorked(); String message = "Congratulations, " + name + "! You have been working here for " + yearsWorked + "."; Manager manager = new Manager(); manager.setEmployee(emp.getName()); // now this employee has been assigned to this manager return manager; } } ``` 我们的`Employee`类如下所示: ```java public class Employee { private String name; private int yearsWorked; public String getName() { return name; } public int getYearsWorked() { return yearsWorked; } } ``` 我们的`Manager`类如下所示: ```java public class Manager { private String employee; public void setEmployee(String name) { employee = name; } public String getEmployee() { return employee; } } ``` ### 分解 就像我上面说的,我们收到的 JSON 格式反序列化为 Java 类型。 当我们说`@RequestBody Employee emp`时,我们将`Employee`类型的方法参数与 Web 请求的主体绑定在一起。`RequestBody`到达如下: ```java { "name": "John Doe", "yearsWorked": "3" } ``` 再次感谢`HttpMessageConverter`方法,我们可以将该`RequestBody` JSON 响应转换为`Employee`对象,该对象包含公共方法`getName()`和`getYearsWorked()`。 这就是为什么我们可以在`RequestBody`参数上调用这些方法的原因: ```java String name = emp.getName();  int yearsWorked = emp.getYearsWorked(); ``` 作为该方法的结果,我们返回了类型为`Manager`的数据,由于`HttpMessageConverter`,我们已将返回类型转换为以下响应格式: ```java { "employee": "the name of the employee that was contained in the @RequestBody" } ``` 附带一提,`RequestBody`注释与`RestController`注释一样,主要用于 REST API。