Spring 4中的@PathVariable验证

14

我如何在Spring中验证我的路径变量。 我想要验证id字段,由于它是单个字段,因此我不想转移到Pojo

@RestController
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(@PathVariable String id) {
        /// Some code
    }
}

我尝试对路径变量添加验证,但仍然无法正常工作。

    @RestController
    @Validated
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(
            @Valid 
            @Nonnull  
            @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters") 
            @PathVariable String id) {
    /// Some code
    }
}

你的代码中没有路径变量,至少在你的URL中没有,所以不确定需要验证什么... - M. Deinum
抱歉,我在复制粘贴代码时错过了它。 - R.A.S.
你可以在 method_name 方法中尝试简单的 if 循环,例如 if(id==null || id.length()<1 || id.length()>2){ String message = "name should have between 1 and 10 characters"; } 如果循环为真,你可以根据需要返回 ResponseEntity。 - Kunal Surana
@R.A.S. 这些答案有帮助到您吗?还是有其他的解决方案或问题? - Patrick
谢谢Patrick,你的解决方案有效。 - R.A.S.
2个回答

19
您需要在Spring配置中创建一个bean:
 @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
    }

你应该在你的控制器上保留@Validated注释。

并且你需要在你的MyController类中添加一个异常处理程序来处理ConstraintViolationException异常:

@ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public String handleResourceNotFoundException(ConstraintViolationException e) {
         Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
         StringBuilder strBuilder = new StringBuilder();
         for (ConstraintViolation<?> violation : violations ) {
              strBuilder.append(violation.getMessage() + "\n");
         }
         return strBuilder.toString();
    }

在进行这些更改后,当验证程序生效时,您应该能够看到您的消息。

附言:我刚才使用了您的@Size验证。


我尝试了你的解决方案,但似乎并没有起作用。唯一的区别是我使用GET方法。这是否需要单独处理? - Nick Div
@NickDiv 不应该是一样的。你遇到了什么问题?也许你应该提出一个问题,并在这里评论它的链接。 - Patrick
@Patrick:你能提供完整的源代码吗?我尝试了但是PathVariable验证仍然失败。 - nguyenngoc101

0
为了实现这个目标,我已经采用了以下解决方法来获取与真正的Validator相等的响应消息:
@GetMapping("/check/email/{email:" + Constants.LOGIN_REGEX + "}")
@Timed
public ResponseEntity isValidEmail(@Email @PathVariable(value = "email") String email) {
    return userService.getUserByEmail(email).map(user -> {
        Problem problem = Problem.builder()
            .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
            .withTitle("Method argument not valid")
            .withStatus(Status.BAD_REQUEST)
            .with("message", ErrorConstants.ERR_VALIDATION)
            .with("fieldErrors", Arrays.asList(new FieldErrorVM("", "isValidEmail.email", "not unique")))
            .build();
        return new ResponseEntity(problem, HttpStatus.BAD_REQUEST);
    }).orElse(
        new ResponseEntity(new UtilsValidatorResponse(EMAIL_VALIDA), HttpStatus.OK)
    );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接