为什么Spring没有运行我的Validator?

时间:2013-03-07 18:03:35

标签: spring spring-mvc

我正在使用Spring MVC并且我正在创建一个Validator,但看起来Spring从未运行它。

这是我的验证器现在很容易检查两个字段

public class MemberRequestValidator  implements Validator {

    public boolean supports(Class aClass) {
        return MemberRequest.class.equals(aClass);
    }

    public void validate(Object obj, Errors errors) {

        MemberRequest mr = (MemberRequest) obj;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content", "Content field is Required");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "areacode", "Area code field is Required");


    }

}

现在我的控制器如下所示:

 @InitBinder("memberrequest")
    public void initMemberRequestBinder(WebDataBinder binder) {
        binder.setValidator(new MemberRequestValidator());
    }



    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveRequest(@ModelAttribute @Valid MemberRequest mr,  BindingResult result)
    {

        if (result.hasErrors())
        {
            LOGGER.debug("Pages had errors on it... returning to input page");
                return new ModelAndView("question");
        }
        else
        {
                String Ticket = mService.sentWebRequest(mr);

                Map<String, Object> model = new HashMap<String, Object>();
                Ticket t = new Ticket();
                t.setTicketDetails(Ticket);

                model.put("ticket", t);

                return new ModelAndView("thanks", model);
        }


    }

在我的JSP页面中,我有以下内容:

 <c:url var="saveUrl" value="/mrequest/save.html" />

            <form:form modelAttribute="memberrequest"  action="${saveUrl}" name="memberrequest" id="memberrequest">

所以,如果我不在表格中输入任何数据,我应该点击错误,但我不是吗?

1 个答案:

答案 0 :(得分:2)

在处理程序中使用@ModelAttribute("memberrequest")或在表单中使用modelAttribute =“memberRequest”并@initBinder("memberRequest")