使用spring mvc注释进行表单验证

时间:2013-05-29 10:39:57

标签: spring-mvc error-handling controller

基于注释表格的工作,我遇到了一些问题,无法获得弹簧验证。

我把它添加到我的spring-servlet.xml

<context:component-scan base-package="com.it.controller" /> (包含我所有控制器的包)

<context:component-scan base-package="com.it.form" /> (包含所有表单类的包)

com.it.form包中的类电子邮件:

public class email {
@NotEmpty
@Email
private String email;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public email() {
    email = "";
    // TODO Auto-generated constructor stub
}

}

表格:

<body>
<form:form method="post" action="" commandName='email'>
    <div class="requestEmail">
        <form:label path="email">Entrez votre email:</form:label>
        <form:input path="email" />
        <form:errors path="email" />
    </div>
    <div>
        <input type="submit" value="VALIDER" />
    </div>
</form:form>

控制器:

@Controller
@SessionAttributes
public class passwordController {

/*
 * ##########################################################
 * 
 * Print & valid form Email
 * 
 * ##########################################################
 */

@RequestMapping(value = "/passwordChange.mvc", method = RequestMethod.GET)
public String get(final ModelMap model) {

    email email= new email();
    model.addAttribute("email", email);
    return "passwordChangeRequestEmail"; // jsp form 
}

@RequestMapping(value = "/passwordChange.mvc", method = RequestMethod.POST)
public String post(final ModelMap model,
        @ModelAttribute("email") @Valid final email email,
        final BindingResult result) {

    if (result.hasErrors()) {
        return "error";
    }
    return "success";
}

}

似乎当我提交表单时,我总是会重定向到/成功页面,即使我将电子邮件输入留空了......

如果我错过了什么话,不知道 在此先感谢:)

1 个答案:

答案 0 :(得分:0)

你必须添加

<mvc:annotation-driven />

到您的servlet上下文文件,并在类路径中导入类似Hibernate Validator的验证器。