【问题标题】:Spring Rest Controller - Get Mapping - At least one Request Parameter mandatorySpring Rest Controller - 获取映射 - 至少需要一个请求参数
【发布时间】:2019-07-18 16:14:13
【问题描述】:

我想将其中一个参数设置为处理获取请求的必需参数。

我需要为此编写自定义验证器吗?

我尝试检查以下方式

if (StringUtils.isEmpty(code) && StringUtils.isEmpty(name) && StringUtils.isEmpty(groupId) && StringUtils.isEmpty(value)) {
      return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }
@GetMapping(
      value = "getByCriteria"
      )
  public @ResponseBody ResponseEntity<ConfigResponse> getByCriteria(
      @RequestParam(value = "groupId", required = false) String groupId,
      @RequestParam(value = "code", required = false) String code,
      @RequestParam(value = "name", required = false) String name,
      @RequestParam(value = "value", required = false) String value) {
// my code here
}

【问题讨论】:

    标签: spring rest validation controller spring-data-jpa


    【解决方案1】:

    您可以在控制器中使用 JSR 验证约束,例如

    import org.springframework.validation.annotation.Validated;
    import javax.validation.constraints.NotBlank;
    
    @RestController
    @RequestMapping("/api")
    @Validated
    public class Controller {
    
        @GetMapping("/hello")
        public String sayHello(@NotBlank @RequestParam String name) {
            return format("Hello %s!", name);
        }
    }
    

    然后根据需要在ControllerAdvice 中处理ConstraintViolationException

    【讨论】:

    • 在我的情况下,我需要任何一个请求参数强制
    • 你可以通过设置required = true来强制它,但要验证参数不是像你的例子那样的空字符串,你需要添加@NonBlank,否则用户可以传递空字符串为一个参数,即使你设置为 required。
    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 2015-10-04
    • 2023-03-09
    • 2020-05-19
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多