微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Boot验证路径变量返回空消息

如何解决Spring Boot验证路径变量返回空消息

我正在使用Spring Boot验证来验证@PathVariable,如下面的代码所示,该验证有效,但是通过curl.exe执行时没有返回消息,我希望收到认消息。

  @GetMapping("/number/{id}")
  String getNumber(@PathVariable @Min(2) Long id) {
        System.out.println("getNumber :" + id);
    return "param id is : " + id;
  }

我指定了一个CustomGlobalExceptionHandler来捕获ConstraintViolationException,并且这样做的原因是返回的http状态代码为400,并且它在控制台日志中显示一条消息“ 必须大于或等于2

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
void onConstraintValidationException(ConstraintViolationException e) {
  System.out.println("in onConstraintValidationException - start");
    String error = "blank";
  for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
      error = violation.getMessage();
      System.out.println(error);
  }
  System.out.println("in onConstraintValidationException - end");
}

我正在使用命令行执行REST服务 curl.exe -v -X GET“ http:// localhost:8080 / demo-0.0.2-SNAPSHOT / number / 1” -H“接受: /

我收到此输出,但没有消息

*Note: Unnecessary use of -X or --request,GET is already inferred.
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /demo-0.0.2-SNAPSHOT/number/1 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.55.1
> accept: */*
>
< HTTP/1.1 400
< transfer-encoding: chunked
< Date: Tue,11 Aug 2020 09:28:06 GMT
< Connection: close
<
* Closing connection 0*

我基于mykong.com示例https://mkyong.com/spring-boot/spring-rest-validation-example/的第3部分。路径变量验证。结果应该匹配的地方

curl -v localhost:8080/books/0

{
    "timestamp":"2019-02-20T13:35:59.808+0000","status":400,"error":"Bad Request","message":"findOne.id: must be greater than or equal to 1","path":"/books/0"
}

您能建议为什么我没有收到返回到命令行的消息吗?

解决方法

您是否将以下注释添加到了控制器中

import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Min;

@RestController
@Validated

您必须实现此类以获取400条消息(而不是500条消息):

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public void constraintViolationException(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }

    //..
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。