如何验证 Spring MVC @PathVariable 值?

新手上路,请多包涵

对于在 Spring MVC 中实现的简单 RESTful JSON api,我可以使用 Bean Validation (JSR-303) 来验证传递到处理程序方法中的路径变量吗?

例如:

  @RequestMapping(value = "/number/{customerNumber}")
 @ResponseBody
 public ResponseObject searchByNumber(@PathVariable("customerNumber") String customerNumber) {
 ...
 }

在这里,我需要使用 Bean 验证来验证 customerNumber 变量的长度。这对 Spring MVC v3.xx 来说可能吗?如果没有,这种类型的验证的最佳方法是什么?

谢谢。

原文由 Grover 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 498
2 个回答

Spring 不支持 @javax.validation.Valid on @PathVariable 处理程序方法中的注释参数。有改进请求,但仍未 解决

您最好的选择是只在处理程序方法主体中进行自定义验证,或者考虑使用 org.springframework.validation.annotation.Validated 如其他答案中所建议的那样。

原文由 Sotirios Delimanolis 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以这样使用:使用 org.springframework.validation.annotation.Validated 有效 RequestParamPathVariable

  *
 * Variant of JSR-303's {@link javax.validation.Valid}, supporting the
 * specification of validation groups. Designed for convenient use with
 * Spring's JSR-303 support but not JSR-303 specific.
 *

步骤1初始化 ValidationConfig

 @Configuration
public class ValidationConfig {
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        return processor;
    }
}

step.2 将 @Validated 添加到您的控制器处理程序类中,例如:

 @RequestMapping(value = "poo/foo")
@Validated
public class FooController {
...
}

step.3 将 validators 添加到您的处理程序方法中:

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Foo> delete(
           @PathVariable("id") @Size(min = 1) @CustomerValidator int id) throws RestException {
        // do something
        return new ResponseEntity(HttpStatus.OK);
    }

最后一步。将异常解析器添加到您的上下文中:

 @Component
public class BindExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex.getClass().equals(BindException.class)) {
            BindException exception = (BindException) ex;

            List<FieldError> fieldErrors = exception.getFieldErrors();
            return new ModelAndView(new MappingJackson2JsonView(), buildErrorModel(request, response, fieldErrors));
        }
    }
}

原文由 BeeNoisy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题