我在我的 Web 应用程序中使用 Spring 4.0 和最新的 Spring Security。我想使用 Hibernate 验证 5.1.1 Final。但它不起作用。相同的代码在我的 JUNIT 中有效,但在 Web 应用程序中无效。
有效的代码:
@Test
public void testUserAuthenticationRequestValidation(){
try{
UserAuthenticationRequest req=new UserAuthenticationRequest().addUserName("bla").addPasswd("passw");
Validator validation=Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<UserAuthenticationRequest>> constraintViolations= validation.validate(req);
Assert.assertTrue("There are some errors", constraintViolations.size()>0);
System.out.println(constraintViolations);
}catch(Exception ex){
ex.printStackTrace();
Assert.fail();
}
但是,如果我尝试在我的 Web 应用程序中使用相同的代码,它就不起作用,在下面的代码中,我希望 contraintViolation 设置不为空,因为我故意将用户名和密码都留空,但我总是发现它是空的.
@Override
public UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
LOGGER.debug("About to check authentication for username: {}", username);
final UserAuthenticationRequest userData = new UserAuthenticationRequest()
.addUserName(username).addPasswd(
authentication.getCredentials().toString());
Validator validation = Validation.buildDefaultValidatorFactory()
.getValidator();
Set<ConstraintViolation<UserAuthenticationRequest>> constraintViolations = validation
.validate(userData);
LOGGER.info("Constraints Violations: {}", constraintViolations);
LOGGER.info("Obejct: username: {} password: {}",
userData.getUsername(), userData.getPasswd());
UserDetailVO userDetailVO = new UserDetailVO(
userInfoService.authenticate(userData));
return userDetailVO;
}
到目前为止,我还徒劳地尝试初始化验证 bean,如下所示并注入我的类,如下所示:
@Configuration
@ComponentScan({ "com.sell.mystuff.web.security",
"com.sell.mystuff.web.service" })
@ImportResource({ "classpath*:spring/common-context.xml" })
public class CommonAppContext {
@Bean(name = "javaxValidator")
public Validator getValidator() {
return Validation.buildDefaultValidatorFactory().getValidator();
}
}
我什至尝试在验证 bean 中显式初始化,如上所示,但似乎没有任何效果。下面是我与验证 api 相关的部分 POM.xml 文件:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.1.1.Final</version>
</dependency>