我有两个模型:User,Project
public class Project{
private int id;
@NotEmpty(message="Project Name can not be empty")
private String name;
private User manager;
private User operator;
//getter/setter omitted
}
public class User{
private int id;
private String name;
//omit other properties and getter/setter
}
现在,当我创建一个新项目时,我将向 ProjectController 提交以下参数:
projects?name=jhon&manager.id=1&operator.id=2...
然后我将创建一个新的 Project 对象并将其插入到 db。
但是我必须验证经理和操作员的 id 是否有效,也就是说我将验证用户表中是否有匹配的 id。
所以我想知道如何实现这种验证?
update1:使用验证器
这是创建新项目的表格:
<sf:form method="${project.id==0?'post':'put'}" commandName="project" action="${context}${action}">
Manager:<sf:input path="manager.id" /> <sf:errors path="manager.id" /> <br />
Operator:<sf:input path="operator.id" /> <sf:errors path="operator.id" /> <br />
Name:<sf:input path="name" /> <sf:errors path="name" /> <br />
<input type="submit" value="Submit" />
</sf:form>
@Override
public void validate(Object obj, Errors errors) {
User user = (User) obj;
int id=user.getId();
User u=userDao.query(id);
if(u==null){
errors.rejectValue("id", "user does not exist!");
}
}
这个验证器似乎有效。
但是,错误消息无法在表单中显示。
然后虽然调试我检查了结果对象,我发现了这个:
org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'project' on field 'id': rejected value [0]; codes [user does not exist!.project.id,user does not exist!.id,user does not exist!.int,user does not exist!]; arguments []; default message [null]
Field error in object 'project' on field 'id': rejected value [0]; codes [user does not exist!.project.id,user does not exist!.id,user does not exist!.int,user does not exist!]; arguments []; default message [null]
结果似乎确实有错误,但它的路径project.id
在我的形式中是project.manager.id
怎么修?