首页 > 代码库 > Spring Validation 表单校验

Spring Validation 表单校验

最近开发一个项目,发现字段校验比较多,同事提出使用Validation校验能更方便一些,今天记录下来,供以后参考:

一、在pom.xml中添加依赖:

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
         <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.1.0.Final</version>
        </dependency>

二、Controller的样例代码:

    @RequestMapping("test.do")
    public String save(@Valid Datasource datasource, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "redirect:edit.do";
        }
    }

三、带有注解的类代码:

public class Datasource extends Common {

    @Size(min = 3, max = 20, message = "用户名长度只能在3-20之间")
    @Pattern(regexp = "\\w+", message = "用户名不能包含特殊字符")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

四、测试:

<form class="form-horizontal" id="datasourceForm" action="/qreport/datasource/save.do" method="post">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">名称</label>
                        <div class="col-sm-10">
                            <input type="text" name="name" value="" class="form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <input type="submit" class="btn btn-primary btn-lg" value="保存">
                    </div>
</form>

名称填写长度不够的字符,那么就会报错,如图: