Spring中的RequestBody注释

时间:2020-02-23 14:34:38  来源:igfitidea点击:

@RequestBody注释可用于处理web请求。

更具体地说,它用于将方法参数与请求的主体绑定,其工作方式是HttpMessageConverter根据请求内容的类型转换请求的主体。

语法

<modifier> <return-type> <method-name> (@RequestBody <type> <name>) {

}

上述语法示例:

public String congratulateEmployee(@RequestBody Employee emp) {

}

包含上述方法的完整控制器类:

@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;
	}	
}

我们的员工班是这样的:

public class Employee {
 private String name;
 private int yearsWorked;

 public String getName() {
    return name;
 }

 public int getYearsWorked() {
    return yearsWorked;
 }
}

我们的经理程序是这样的:

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请求的主体。请求主体如下所示到达:

{
 "name": "John Doe", 
 "yearsWorked": "3"
}

再次感谢HttpMessageConverter方法,我们可以将RequestBody JSON响应转换为Employee对象,其中包含公共方法*getName()GetYearsWorlded()。*这就是为什么我们可以对RequestBody参数调用这些方法的原因:

String name = emp.getName(); 
int yearsWorked = emp.getYearsWorked();

作为该方法的结果,我们返回了“Manager”类型的数据,由于使用了HttpMessageConverter,我们将返回类型转换为以下响应格式:

{
"employee": "the name of the employee that was contained in the @RequestBody"
}

另外,RequestBody注释和RestController注释一样,主要用于restapi。