不允许 {} 作为请求体

huangapple go评论98阅读模式
英文:

do not allow {} as request body

问题

我有以下的POST方法处理程序:

@PostMapping("/endpoint")
public int myEndpoint(@RequestBody MyBody body) {
    return body.foo;
}

它接受以下的请求体:

class MyBody {
    private int foo;

    public MyBody() {}

    public MyBody(int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return this.foo;
    }
}

现在,我期望当我使用{}作为请求体向/endpoint发出请求时,它会返回状态码400,但我却得到了状态码200和body.foo的值是0。

我该如何确保{}的请求体被拒绝?

英文:

I have the following post method handler:

@PostMapping("/endpoint")
public int myEndpoint(@RequestBody MyBody body) {
    return body.foo;
}

Which accepts the following request body:

class MyBody {
    private int foo;

    public MyBody() {}

    public MyBody(foo) {
        this.foo = foo;
    }

    public getFoo() {
        return this.foo;
    }
}

Now, I expect that when I make request to /endpoint with body {} It'll return status 400,

but I get 200 and body.foo is 0.

How can I make sure {} body is rejected?

答案1

得分: 1

您可以使用注解验证请求体

```java
@PostMapping("/endpoint")
public int myEndpoint(@RequestBody @Valid MyBody body) {
    return body.foo;
}

您还需要添加验证依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

然后,MyBody 是一个数据传输对象(DTO),不要使用原始类型如 int,因为它们具有默认值。添加您需要的验证:

class MyBody {
    @NotNull
    private Integer foo;

    ...
}
英文:

You could validate the body with annotations :

@PostMapping(&quot;/endpoint&quot;)
public int myEndpoint(@RequestBody @Valid MyBody body) {
    return body.foo;
}

you also need to add validations dependencie

&lt;dependency&gt; 
	    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; 
	    &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt; 
&lt;/dependency&gt;

then MyBody is a DTO, don't use primitive types as int since they have a default value. Add the validations you need :

class MyBody {
    @NotNull
    private Integer foo;

    ...
}

huangapple
  • 本文由 发表于 2020年8月14日 03:05:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63401688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定