码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中的DataBinding(二) - Validation

时间:2015-04-13 18:39:13      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:


@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

标签:

原文地址:http://www.cnblogs.com/ygshen/p/4422777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!