spring - Spring 4 中的@PathVariable 验证

标签 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
    }
}

最佳答案

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

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

您应该在 Controller 上保留 @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 验证进行了尝试。

关于spring - Spring 4 中的@PathVariable 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403744/

相关文章:

java - 将方面添加到实现类而不是接口(interface)

java - 无法将 Spring-data 的依赖添加到 Spring boot 中

java - Spring Security——检索当前尝试登录的用户的用户名

java - 一个类的多个Bean配置

java - 动态字段 thymeleaf 列表迭代

java - 如何放置<安全:authentication property ="principal.username"/> inside a value ="" in an input?

java - Spring 4 MVC 区域设置已更改,但 JSP 对此没有响应

java - Spring Security 'remember me' cookie 在第一个请求中不可用

grails - springSecurityService.getCurrentUser()返回错误没有这样的属性:类的标识:java.lang.String

java - 有什么方法可以从 spring 上下文中获取 Hibernate SequenceGenerator 吗?