spring boot Controller中使用注解@RequestBody遇到的一個問題總結:
通過@RequestBody接收實體對象,如代碼所示
@PostMapping(value = "addtype")
public Object addAppType(@RequestBody AppType appType) throws Exception{
return JsonData.buildSuccess();
}
用postman測試接口時,
- 首先選擇post請求
- 然后Header中添加"Content-Type:application/json"
- 如圖:
- Body中選擇"raw",並選擇"JSON(application/json)"
- 如圖:
這樣配置以后就可以發送post請求測試spring boot的post接口。
踩的坑:
postman中body選擇了"x-www-form-urlencoded",發送請求。報錯如下(這個貌似是外部tomcat報的錯):
<!doctype html><html lang="en"><head><title>HTTP Status 404 ? Not Found</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 ? Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/9.0.10</h3></body></html>
如果此時postman請求方式選擇成put也會報這個錯。(很奇怪,猜測是不是外部tomcat把實際錯誤給屏蔽了?)
除此之外 我發現使用postman中body選擇了"x-www-form-urlencoded"后,controller里面就不能寫@RequestBody了,直接用實體類接收就可以接收到數據。代碼如下:
@PostMapping(value = "addtype") public Object addAppType(AppType appType) throws Exception{return JsonData.buildSuccess(); }
但是此方式貌似沒什么用,因為spring boot + vue前端訪問接口時,都是json格式。。。