Spring RequestBody 与 Postman 测试

Spring RequestBody with Postman testing

我正在测试我的应用程序,我发现了一些奇怪的东西。

我的代码:

  @RequestMapping(value = "/test/{subscriberId}", method = RequestMethod.PATCH, consumes = "application/json", produces = "application/json")
public void test(@PathVariable final String subscriberId,@RequestBody Boolean actDeact ) {
..
}

当我通过邮递员发出请求时,我接受了 400 个错误请求:

但是当我在 body 中只传递 true 时,一切正常:

我不明白为什么会这样。

我认为我的第一次尝试是有效的。如果我等待一个字符串,也会发生同样的情况 (我没有收到错误代码 400,但将字符串中的所有 body 传递给我)

谁能解释一下?

布尔值的反序列化只是一个布尔值。例如:真

如果你想接受第一种方式的参数,你应该通过一个dto对象来接受这个参数。

示例:

public class ActDeactDto {
    public boolean actDeact;
}

@RequestMapping(value = "/test/{subscriberId}", method = 
RequestMethod.PATCH, consumes = "application/json", produces = 
"application/json")
public void test(@PathVariable final String subscriberId, @RequestBody 
ActDeactDto actDeact ) {
..
}

这样试试:

 public class MyPojo
    {
  private  Boolean actDeact;
  private  String subscriberId;
    // you can add it if you want more ..

    public Boolean getActDeact() {
        return actDeact;
    }

    public void setActDeact(Boolean actDeact) {
        this.actDeact = actDeact;
    }

   public String getSubscriberId() {
    return subscriberId;
   }
   public void setSubscriberId(String subscriberId) {
    this.subscriberId = subscriberId;
   } 
 }

@RequestBody MyPojo myPojo // 像这样使用它。

Spring 会将传入的 JSON 转换为来自 post body 的 MyPojo object (因为您添加了 @RequestBody 注释)并且它会将 returned object 序列化为 JSON (因为您添加了 @ResponseBody 注释)。

你可以参考 https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc 更多。

注:

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

@RequestParam 可以用来发送: String,Boolean 作为参数,没有包装器。

同理

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

那么你发送 true 的地方 这不是 body with method 。 它无法工作或转换为 json 所以它会 return 某些东西 400 状态码

400 Bad Request 响应代码的扩展。 如果您仍然需要了解更多信息,可以阅读文档 弹簧。 我希望这可以帮助你.... 谢谢..

原则上应该检查HTTP方法之间使用的一致性。在 Postman 中,您正在使用 POST,但在您的 RequestMapping 方法中使用 PATCH