如何验证 Spring MVC @PathVariable 值? [英] How to validate Spring MVC @PathVariable values?

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

问题描述

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

For a simple RESTful JSON api implemented in Spring MVC, can I use Bean Validation (JSR-303) to validate the path variables passed into the handler method?

例如:

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

在这里,我需要使用 Bean 验证来验证 customerNumber 变量的长度.Spring MVC v3.x.x 可以做到这一点吗?如果不是,这种类型的验证的最佳方法是什么?

Here, I need to validate the customerNumber variables's length using Bean validation. Is this possible with Spring MVC v3.x.x? If not, what's the best approach for this type of validations?

谢谢.

推荐答案

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

Spring does not support @javax.validation.Valid on @PathVariable annotated parameters in handler methods. There was an Improvement request, but it is still unresolved.

最好的办法是在处理程序方法体中进行自定义验证,或者考虑使用其他答案中建议的 org.springframework.validation.annotation.Validated.

Your best bet is to just do your custom validation in the handler method body or consider using org.springframework.validation.annotation.Validated as suggested in other answers.

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

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