Spring Rest Controller-获取映射-至少需要一个请求参数

时间:2019-07-18 16:14:13

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

我想将参数之一作为处理获取请求的必需参数。

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

我尝试通过以下方式进行检查

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
}

1 个答案:

答案 0 :(得分:0)

您可以在控制器中使用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);
    }
}

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