Spring 4中的@PathVariable验证

时间:2016-02-15 07:32:46

标签: spring spring-mvc spring-security spring-boot spring-data

如何在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
    }
}

3 个答案:

答案 0 :(得分:17)

您需要在Spring配置中创建一个bean:

 @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
    }

您应该在控制器上留下@Validated注释。

您需要在MyController课程中使用Exceptionhandler来处理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();
    }

完成这些更改后,您应该在验证到达时看到您的消息。

P.S。:我刚用@Size验证试了一下。

答案 1 :(得分: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)
    );
}

答案 2 :(得分:-1)

我认为这是@RequestMapping("/")的问题 将@RequestMapping("/")添加到您的休息类,然后使用@pathVariable

@RestController
@RequestMapping("/xyz")
public class MyController {

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