2013-05-29 42 views
0

基於註解形式的工作,我得到了一些麻煩來獲得spring驗證。使用spring mvc註解進行表單驗證

我將此添加到我的彈簧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

假設你有Hibernate驗證器依賴項'hibernate-validator'來處理JSR303註釋? –

+0

是的。我找到了解決方案,我沒有包含 .. :(我認爲就夠了。 – MinionKing

回答

0

你必須

<mvc:annotation-driven /> 

添加到您的servlet上下文的文件並導入像Hibernate驗證驗證程序在你的類路徑中。