【发布时间】:2011-09-07 19:48:18
【问题描述】:
我的应用程序中有一个需要验证的用户实体。
public class User {
private String userName;
private String password;
public void setUserName(String userName){
this.userName = userName;
}
public getUserName(){
return this.userName;
}
// and so on
}
为此,我创建了如下所示的 UsersValidator。
public class UserValidator implements Validator {
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
}
}
我有一个这样的控制器
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String home(@Valid User user,
BindingResult result) {
if (result.hasErrors()) {
return "loginForm";
} else {
//continue
}
}
绑定结果没有任何错误。
我还需要做什么才能使验证生效?我是否对控制器或弹簧配置文件进行了任何更改。
<mvc:annotation-driven />
<context:component-scan base-package="com.myapp" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.tiles2.TilesView</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>com/dimex/resourceBundles/ApplicationResources</value>
<value>com/dimex/resourceBundles/errors</value>
</list>
</property>
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale"></property>
</bean>
</mvc:interceptors>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
编辑:-
我需要在我的类路径中有休眠验证器吗?我们没有在我们的应用程序中使用休眠。 请帮忙。
EDIT2:-
当我直接在我的实体类中使用验证注释(@NotNull、@Size 等)时,控制器中的 @Valid 注释可以工作,但如果我从实体中删除它们并尝试使用上面编写的验证器,那么 @Valid 不起作用.
是不是@Valid 注释只适用于实体中的验证注释而不适用于验证器?为了使用我的验证器,我必须直接在验证器中调用 validate 方法吗?
【问题讨论】:
-
你配置spring来实例化UserValidator了吗?例如,通过使用
@Component注释验证器?如果使用 @NotNull 注释 bean 上的字段,也可以实现几乎相同的行为。 -
@Augusto 我已经添加了@Component 但它仍然无法正常工作!!!!!!
-
您还需要
<context:component-scan/>才能获取@Components。你有这个吗?如果你发布你的 Spring XML 会更容易。 -
@matt b 我已经用 Spring xml 更新了这个问题。
-
如果我明确执行 this.validator.validate(user, result);那么它的工作,但如果我使用@Valid 那么它不工作。
标签: java validation spring-mvc