Spring 3 - 基于注解的 Bean 验证 [英] Spring 3 - Annotation based Bean Validation
问题描述
我正在构建一个 REST API.它由一个资源(@Controller)组成,即使其中一个必填字段不存在,它也会返回响应 204.
I am building a REST API. Its made up of a Resource ( @Controller ) which returns a response 204 even when one of the mandatory field is not present.
我使用的是 Spring 3.1,validation-api (1.1.0.Final) &休眠验证器(4.3.0).不确定 Hibernate-validator 是否在这里起作用.
I am using Spring 3.1, validation-api (1.1.0.Final) & Hibernate-validator(4.3.0). Not sure if Hibernate-validator plays any role here.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
</exclusions>
</dependency>
我有一个弹簧控制器@Controller 和一个带有@Component 的 Bean
I have a spring controller @Controller and a Bean with @Component
@POST
@Consumes(value = {MediaType.APPLICATION_JSON})
@Produces(value = {MediaType.APPLICATION_JSON})
@RequestMapping(method = RequestMethod.POST)
public Response addUserData(@Valid @RequestBody UserData userDataRequest) throws ResourceException {
...
}
我的 UserData bean 有
My UserData bean has
@Component
public class UserData {
@NotNull(message = "user ID should not be null")
@Min(value = 1, message = "user ID should not be empty")
@Max(value = 20, message = "user ID should have length of more than 20")
@Pattern(regexp="[A-Z][a-z]+", message = "Only Alphanumeric characters allowed")
private String userId;
}
我的验证没有得到执行.当我不传递userId"时,不会抛出任何错误.我在这里错过了什么?
My validations are not getting executed. When I dont pass "userId", there is no error thrown. What am I missing here ?
推荐答案
我最终使用 Jersey Bean Validation 而不是 Spring.这是因为我的其余代码无论如何都在使用 Jersey.为了完成这项工作,我刚刚导入了 Jersey Bean Validation jar 并对 web.xml 添加了一个小改动.验证现在正在运行.
I ultimately ended up using Jersey Bean Validation, instead of Spring. This is because rest of my code is using Jersey anyways. To make this work I just imported Jersey Bean Validation jar and added a small change to web.xml. Validations are now working.
谢谢@Manual Jordan.我会赞成你的回答,因为它给了我正确的线索.
Thank you @Manual Jordan. I will upvote your answer, since it gave me the right clues.
<!-- jersey beanValidation -->
<init-param>
<param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
<param-value>true</param-value>
</init-param>
这篇关于Spring 3 - 基于注解的 Bean 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!