我正在使用spring进行休息网络服务,我试图验证收到的对象:
@RequestMapping(value="/sendResult", method = RequestMethod.POST)
public @ResponseBody String createResult(@Valid Result result, @RequestParam("image") MultipartFile image) {
}
这是结果模型中的验证方法:
@AssertTrue(message="votesCast field should be less or equal than registredVoters field")
private boolean isValid() {
return ((this.votesCast <= this.registredVoters) && (this.votesCast == this.validVotes + this.invalidVotes) );
}
我的问题是如何使我的验证约束可配置,我发现Hibernate validator constraints in XML。 但是这样如何将字段比较放在XML文件中,就像我在isValid方法中所做的那样? 提前致谢
答案 0 :(得分:0)
您可以在实体类中验证您的模型,如下所示:
public class MultipartFile {
@Size(min = 3, max = 20)
String name;
//...
}
默认情况下,您的错误消息为
大小必须在3到20之间。
要更改消息,您应该使用如下注释:
@Size(min = 3, max = 20, message = "your own message")
或者您可以在资源目录中创建ValidationMessages.properties文件,并写入如下内容:
javax.validation.constraints.Size.message = Size must be between {min} and {max}. It is my own error message!
在你的Post方法中会是这样的:
@RequestMapping(value="/sendResult", method = RequestMethod.POST)
public @ResponseBody String createResult(@ModelAttribute("image") @Valid
MultipartFile image, BindingResult result) {
if (result.hasErrors()) {
//...
} else {
//...
}
}
也许你需要这样的东西:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="USER">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
</class>
</hibernate-mapping>
答案 1 :(得分:0)
它可以帮助你。使用Spring Validator接口验证您的值
public class ResultValidator implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return Result.class.isAssignableFrom(aClass);
}
@Override
public void validate(Object o, Errors errors) {
Result r = (Result)o;
if(r.votesCast > r.registredVoters){
errors.rejectValue("registredVoters","RegistredVoters is not valid")
}
if(r.votesCast != r.validVotes + r.invalidVotes)){
errors.rejectValue("votesCast","VotesCast is not valid")
}
}
rejectValue
参数:
此外,您可以使用ValidationUtils
来检查空值和空格。
2.在您的控制器中添加以下代码:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new ResultValidator());
}
3.只需在方法参数中添加@Valid注释。
检查相关帖子:http://javainsimpleway.com/spring-mvc-form-validation-with-custom-validator/