Bean验证@Positive指令不适用于Integer @PathVariable [英] Bean validation @Positive directive is not working on Integer @PathVariable

查看:117
本文介绍了Bean验证@Positive指令不适用于Integer @PathVariable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用@Positive bean验证注释来验证控制器方法(REST Api资源)Integer参数,但是什么也没发生.

I'm trying to validate a controller method (REST Api resource) Integer parameter with @Positive bean validation annotation, but nothing happens.

Java:
Java版本"11.0.2" 2019-01-15 LTS
Java(TM)SE运行时环境18.9(内部版本11.0.2 + 9-LTS)
Java HotSpot(TM)64位服务器VM 18.9(内部版本11.0.2 + 9-LTS,混合模式)

春季靴:
2.1.6.发布

Java:
Java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

Spring Boot:
2.1.6.RELEASE

代码:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/{id}")
    public ResponseEntity<?> lista(@Valid @NotNull @Positive @PathVariable("id") Integer id) {
        String msg = "";
        if (id > 0) {
            msg = "id > 0";
        } else {
            msg = "id <= 0";
        }
        System.out.println(msg);
        return ResponseEntity.ok(msg);
    }
}


@Positive 并未执行应做的事情.


The @Positive is not doing what it is supposed to do.

测试:

请求:
GET本地主机:8080/test/0
回应:
200 OK"id< = 0"
预期:
400错误的请求

请求:
GET本地主机:8080/test/-1
回应:
200 OK"id< = 0"
预期:400错误请求


当我尝试GET localhost:8080/test/teste时,按预期收到400错误请求.

Tests:

Request:
GET localhost:8080/test/0
Response:
200 OK "id <= 0"
Expected:
400 Bad Request

Request:
GET localhost:8080/test/-1
Response:
200 OK "id <= 0"
Expected:400 Bad Request


When I try GET localhost:8080/test/teste, I receive a 400 Bad Request, as expected.

推荐答案

遇到了相同的问题,并通过应用解决了该问题

Had the same problem and solved it by applying

@Validated

在我的控制器上.那应该不是HTTP 400,而是HTTP 500.

on my controller. That should give you not HTTP 400 but HTTP 500.

这篇关于Bean验证@Positive指令不适用于Integer @PathVariable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆