Spring表单验证错误

时间:2014-07-24 09:40:53

标签: spring validation spring-mvc

当我使用v form validatio验证输入时,我的spring mvc应用程序有一个表单输入框,它会在服务器上抛出错误... 我也在messages.properties文件上设置了错误消息。

错误

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: validation failed for classes [com.company.product.domain.Rating] during persist time for groups [javax.validation.groups.Default, ]

评分域

  @Entity
    @Table(name = "rating")
    public class Rating {
        int id;
        @NotEmpty
        String name;
        Date createdDate;
        boolean isDelete;

        getter,setter
    }

在我的域名中,我为一个字段设置了验证 - “名称”

控制器

@RequestMapping(value =“/ add-rating”)

public String addRating(@ModelAttribute(value = "rating") Rating rating,BindingResult result) {
    if(result.hasErrors()){
        return "/secure/admin/rating";
    }
    java.util.Date utilDate = new java.util.Date();
    Date sqlDate = new Date(utilDate.getTime());
    rating.setCreatedDate(sqlDate);
    ratingService.saveRating(rating);
    return "redirect:/rating";
}

为什么不验证表单错误?

1 个答案:

答案 0 :(得分:1)

您尚未指示Spring运行验证过程。 为此,您需要添加@Valid

@RequestMapping(value = "/add-rating")
public String addRating(@Valid @ModelAttribute(value = "rating") Rating rating,BindingResult result) {
    if(result.hasErrors()){
        return "/secure/admin/rating";
    }
    java.util.Date utilDate = new java.util.Date();
    Date sqlDate = new Date(utilDate.getTime());
    rating.setCreatedDate(sqlDate);
    ratingService.saveRating(rating);
    return "redirect:/rating";
}

查看this教程以获取更多信息。