spring boot Controller中使用注解@RequestBody遇到的一个问题

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格式。。。

猜你喜欢

转载自www.cnblogs.com/jiangbo2018/p/9372757.html