Spring 4 中的@PathVariable 验证 [英] @PathVariable Validation in Spring 4

查看:35
本文介绍了Spring 4 中的@PathVariable 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 spring 中验证我的路径变量.我想验证 id 字段,因为它只有一个字段,我不想移动到 Pojo

How can i validate my path variable in spring. I want to validate id field, since its only single field i do not want to move to a Pojo

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

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

I tried doing adding validation to the path variable but its still not working

    @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
    }
}

推荐答案

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

You need to create a bean in your Spring configuration:

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

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

You should leave the @Validated annotation on your controller.

并且您需要在 MyController 类中使用一个 Exceptionhandler 来处理 ConstraintViolationException :

And you need an Exceptionhandler in your MyController class to handle theConstraintViolationException :

@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() + "
");
         }
         return strBuilder.toString();
    }

进行这些更改后,您应该会在验证成功时看到您的消息.

After those changes you should see your message when the validation hits.

P.S.:我刚刚用你的 @Size 验证试过了.

P.S.: I just tried it with your @Size validation.

这篇关于Spring 4 中的@PathVariable 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆