JavaSpring框架表单验证

JavaSpring框架表单验证,java,forms,model-view-controller,spring,validation,Java,Forms,Model View Controller,Spring,Validation,我使用的是SpringFramework 3.0.5 我有一张表格: <form:form method="POST" modelAttribute="postedEntry"> Category: <form:select path="category" items="${menus}" itemValue="id" itemLabel="menuName"/><form:errors path="category"/> <br/>

我使用的是SpringFramework 3.0.5

我有一张表格:

<form:form method="POST" modelAttribute="postedEntry">
    Category: <form:select path="category" items="${menus}" itemValue="id" itemLabel="menuName"/><form:errors path="category"/>
    <br/>Title: <form:input path="title"/><form:errors path="title"/>
    <br/>Short Description: <form:textarea path="shortDesc"/><form:errors path="shortDesc"/>
    <br/>Body: <form:textarea path="body"/><form:errors path="body"/>
    <br/><input type="submit" value="POST IT!11"/>
</form:form>
以及控制器:

@RequestMapping(value="/entryPost",method=RequestMethod.POST)
public String entryPost(@ModelAttribute("postedEntry") Entry entry,BindingResult result){
    entryValidator.validate(entry, result);
    if(result.hasErrors()){
        return "entryPost";
    }else{
        rusService.postEntry(entry);
        return "redirect:entryPost";
    }
}
在我的服务对象中:

public void postEntry(final Entry entry){
    String sql = "INSERT INTO entries (category,title,shortDesc,body,date) VALUES(?,?,?,?,?)";
    jdbcTemplate.update(sql,new Object[]{entry.getCategory(),entry.getTitle(),entry.getShortDesc(),entry.getBody(),entry.getDate()});
}
和验证程序:

public class EntryValidator implements Validator{
    public boolean supports(Class clazz){
        return Entry.class.isAssignableFrom(clazz);
    }
    public void validate(Object target,Errors errors){
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "category", "required.category","Category is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "required.title", "Title is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "shortDesc","required.shortDesc", "Short description is required!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "body", "required.body", "Body is required!");
        Entry entry = (Entry) target;
        entry.setDate(new Date());
    }
}
如果有人发送类别的字符串值,而不是整数,它将在表单附近键入: 无法将java.lang.String类型的属性值转换为属性类别所需的int类型;嵌套异常为org.springframework.core.convert.ConversionFailedException:无法将值“h”从java.lang.String类型转换为int类型;嵌套异常为java.lang.NumberFormatException:用于输入字符串:“h”

但我不想让它打这个。我如何验证这个值并抛出自己的消息? 我试图通过添加以下内容在我的验证器中进行检查:

int cat = entry.getCatrgory();
if(cat.equals("0"))
    errors.reject("invalid.category","The category is invalid!");
但是它没有工作-它仍然抛出ConversionFailedException异常。

您需要为错误消息声明一个异常。然后您可以为其中的类型不匹配错误指定消息,如下所示:(也可以在此处指定其他错误消息)。

您可以使用资源包中的密钥

例如:

typeMismatch = This is not a number!
typeMismatch = This is not a number!