標籤:
@Controller
@RequestMapping(value = "/custom/register")
public class RegistrationController {
// Set the data binding per controller @InitBinder public void initBinder(WebDataBinder binder){ binder.setDisallowedFields("id");
// 此處指定在綁定的時候存在兩個必須欄位 binder.setRequiredFields("userName","password"); }
// POST請求的時候將BindingResult的對象置於參數列表中。 BindingResult是<form: error> 這個tag的子類。 @RequestMapping(method = {RequestMethod.POST,RequestMethod.PUT}) public String handleRegistration(Account account, BindingResult result){
// 校正過程中如果存在error返回到本頁,而且本頁中有一個DataModel為Result if(result.hasErrors()) return "custom/register"; accountService.SaveAccount(account); return "redirect:custom/account/"+account.getId(); }
}
JSP檔案中,在相應的控制項處添加Error 標籤,這樣如果BindingResult不為空白。這些Error 標籤就會將提示資訊顯示出來
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2015/4/6 Time: 22:16 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@taglib prefix="spring" uri="http://www.springframework.org/tags" %><%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %><html><head> <title>Registration Page</title></head><body><form:form modelAttribute="account" method="post"> <fieldset> <legend> Account Personal Information </legend> <table> <tr> <td>FirstName</td> <td> <form:input path="firstName"></form:input> </td> </tr> <tr> <td>LastName</td> <td> <form:input path="lastName"></form:input> </td> </tr> </table> </fieldset> <fieldset> <legend>Account information</legend> <table> <tr> <td>User Name</td> <td><form:input path="userName"></form:input></td> <td><form:errors path="userName"></form:errors> </td> </tr> <tr> <td><form:label path="password">Password</form:label></td> <td><form:input path="password"></form:input></td> <td><form:errors path="password"></form:errors> </td> </tr> </table> </fieldset> <form:button value="Submit">提交 </form:button></form:form></body></html>
Spring中的DataBinding(二) - Validation