作者:ssslinppp      

1.准备



这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://hibernate.org/validator/下载需要的jar包,这里以4.3.1.Final作为演示,解压后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中。

2. Spring MVC上下文配置




    1. <?xml version="1.0" encoding="UTF-8" ?>
    1. <beans xmlns="http://www.springframework.org/schema/beans"
    1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    1. xmlns:context="http://www.springframework.org/schema/context"
    1. xmlns:mvc="http://www.springframework.org/schema/mvc"
    1. xsi:schemaLocation="http://www.springframework.org/schema/beans
    1. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    1. http://www.springframework.org/schema/context
    1. http://www.springframework.org/schema/context/spring-context-3.0.xsd
    1. http://www.springframework.org/schema/mvc
    1. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    1. <!-- 扫描web包,应用Spring的注解 -->
    1. <context:component-scan base-package="com.ll.web"/>
    1. <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面,默认优先级最低 -->
    1. <bean
    1. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    1. p:viewClass="org.springframework.web.servlet.view.JstlView"
    1. p:prefix="/jsp/"
    1. p:suffix=".jsp" />
    1. <!-- 设置数据校验、数据转换、数据格式化 -->
    1. <mvc:annotation-driven validator="validator" conversion-service="conversionService"/>
    1. <!-- 数据转换/数据格式化工厂bean -->
    1. <bean id="conversionService"
    1. class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
    1. <!-- 设置校验工厂bean-采用hibernate实现的校验jar进行校验-并设置国际化资源显示错误信息 -->
    1. <bean id="validator"
    1. class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    1. <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
    1. <!--不设置则默认为classpath下的 ValidationMessages.properties -->
    1. <property name="validationMessageSource" ref="validatemessageSource" />
    1. </bean>
    1. <!-- 设置国际化资源显示错误信息 -->
    1. <bean id="validatemessageSource"
    1. class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    1. <property name="basename">
    1. <list>
    1. <value>classpath:valideMessages</value>
    1. </list>
    1. </property>
    1. <property name="fileEncodings" value="utf-8" />
    1. <property name="cacheSeconds" value="120" />
    1. </bean>
    1. </beans>

3. 待校验的Java对象



    1. package com.ll.model;
    1. import java.util.Date;
    1. import javax.validation.constraints.DecimalMax;
    1. import javax.validation.constraints.DecimalMin;
    1. import javax.validation.constraints.Past;
    1. import javax.validation.constraints.Pattern;
    1. import org.hibernate.validator.constraints.Length;
    1. import org.springframework.format.annotation.DateTimeFormat;
    1. import org.springframework.format.annotation.NumberFormat;
    1. public class Person {
    1. @Pattern(regexp="W{4,30}",message="{Pattern.person.username}")
    1. private String username;
    1. @Pattern(regexp="S{6,30}",message="{Pattern.person.passwd}")
    1. private String passwd;
    1. @Length(min=2,max=100,message="{Pattern.person.passwd}")
    1. private String realName;
    1. @Past(message="{Past.person.birthday}")
    1. @DateTimeFormat(pattern="yyyy-MM-dd")
    1. private Date birthday;
    1. @DecimalMin(value="1000.00",message="{DecimalMin.person.salary}")
    1. @DecimalMax(value="2500.00",message="{DecimalMax.person.salary}")
    1. @NumberFormat(pattern="#,###.##")
    1. private long salary;
    1. public Person() {
    1. super();
    1. }
    1. public Person(String username, String passwd, String realName) {
    1. super();
    1. this.username = username;
    1. this.passwd = passwd;
    1. this.realName = realName;
    1. }
    1. public String getUsername() {
    1. return username;
    1. }
    1. public void setUsername(String username) {
    1. this.username = username;
    1. }
    1. public String getPasswd() {
    1. return passwd;
    1. }
    1. public void setPasswd(String passwd) {
    1. this.passwd = passwd;
    1. }
    1. public String getRealName() {
    1. return realName;
    1. }
    1. public void setRealName(String realName) {
    1. this.realName = realName;
    1. }
    1. public Date getBirthday() {
    1. // DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    1. // return df.format(birthday);
    1. return birthday;
    1. }
    1. public void setBirthday(Date birthday) {
    1. this.birthday = birthday;
    1. }
    1. public long getSalary() {
    1. return salary;
    1. }
    1. public void setSalary(long salary) {
    1. this.salary = salary;
    1. }
    1. @Override
    1. public String toString() {
    1. return "Person [username=" + username + ", passwd=" + passwd + "]";
    1. }
    1. }

4. 国际化资源文件





5. 控制层




下面这张图是从其他文章中截取的,主要用于说明:@Valid与BindingResult之间的关系;

    1. package com.ll.web;
    1. import java.security.NoSuchAlgorithmException;
    1. import javax.validation.Valid;
    1. import org.springframework.stereotype.Controller;
    1. import org.springframework.validation.BindingResult;
    1. import org.springframework.web.bind.annotation.ModelAttribute;
    1. import org.springframework.web.bind.annotation.RequestMapping;
    1. import com.ll.model.Person;
    1. /**
    1. * @author Administrator
    1. *
    1. */
    1. @Controller
    1. @RequestMapping(value = "/test")
    1. public class TestController {
    1. @ModelAttribute("person")
    1. public Person initModelAttr() {
    1. Person person = new Person();
    1. return person;
    1. }
    1. /**
    1. * 返回主页
    1. * @return
    1. */
    1. @RequestMapping(value = "/index.action")
    1. public String index() {
    1. return "regedit";
    1. }
    1. /**
    1. * 1. 在入参对象前添加@Valid注解,同时在其后声明一个BindingResult的入参(必须紧随其后),
    1. * 入参可以包含多个BindingResult参数;
    1. * 2. 入参对象前添加@Valid注解:请求数据-->入参数据 ===>执行校验;
    1. * 3. 这里@Valid在Person对象前声明,只会校验Person p入参,不会校验其他入参;
    1. * 4. 概括起来:@Valid与BindingResult必须成对出现,且他们之间不允许声明其他入参;
    1. * @param bindingResult :可判断是否存在错误
    1. */
    1. @RequestMapping(value = "/FormattingTest")
    1. public String conversionTest(@Valid @ModelAttribute("person") Person p,
    1. BindingResult bindingResult) throws NoSuchAlgorithmException {
    1. // 输出信息
    1. System.out.println(p.getUsername() + " " + p.getPasswd() + " "
    1. + p.getRealName() + " " + " " + p.getBirthday() + " "
    1. + p.getSalary());
    1. // 判断校验结果
    1. if(bindingResult.hasErrors()){
    1. System.out.println("数据校验有误");
    1. return "regedit";
    1. }else {
    1. System.out.println("数据校验都正确");
    1. return "success";
    1. }
    1. }
    1. }

6. 前台




引入Spring的form标签:

在前台显示错误:


    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    1. <html>
    1. <head>
    1. <title>数据校验</title>
    1. <style>
    1. .errorClass{color:red}
    1. </style>
    1. </head>
    1. <body>
    1. <form:form modelAttribute="person" action='FormattingTest.action' >
    1. <form:errors path="*" cssClass="errorClass" element="div"/>
    1. <table>
    1. <tr>
    1. <td>用户名:</td>
    1. <td>
    1. <form:errors path="username" cssClass="errorClass" element="div"/>
    1. <form:input path="username" />
    1. </td>
    1. </tr>
    1. <tr>
    1. <td>密码:</td>
    1. <td>
    1. <form:errors path="passwd" cssClass="errorClass" element="div"/>
    1. <form:password path="passwd" />
    1. </td>
    1. </tr>
    1. <tr>
    1. <td>真实名:</td>
    1. <td>
    1. <form:errors path="realName" cssClass="errorClass" element="div"/>
    1. <form:input path="realName" />
    1. </td>
    1. </tr>
    1. <tr>
    1. <td>生日:</td>
    1. <td>
    1. <form:errors path="birthday" cssClass="errorClass" element="div"/>
    1. <form:input path="birthday" />
    1. </td>
    1. </tr>
    1. <tr>
    1. <td>工资:</td>
    1. <td>
    1. <form:errors path="salary" cssClass="errorClass" element="div"/>
    1. <form:input path="salary" />
    1. </td>
    1. </tr>
    1. <tr>
    1. <td colspan="2"><input type="submit" name="提交"/></td>
    1. </tr>
    1. </table>
    1. </form:form>
    1. </body>
    1. </html>


7. 测试



8. 其他

参考链接:
淘宝源程序下载(可直接运行):




附件列表

【Spring学习笔记-MVC-10】Spring MVC之数据校验的更多相关文章

  1. 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  2. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  3. 【Spring学习笔记-MVC-7】Spring MVC模型对象-模型属性讲解

    作者:ssslinppp       来自为知笔记(Wiz) 附件列表 处理模型数据.png

  4. 【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问

    作者:ssslinppp       参考链接: http://www.cnblogs.com/luxh/archive/2013/03/14/2959207.html  http://www.cnb ...

  5. 【Spring学习笔记-MVC-16】Spring MVC之重定向-解决中文乱码

    概述 spring MVC框架controller间跳转,需重定向,主要有如下三种: 不带参数跳转:形如:http://localhost:8080/SpringMVCTest/test/myRedi ...

  6. 【Spring学习笔记-MVC-15】Spring MVC之异常处理

    作者:ssslinppp       1. 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理 ...

  7. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

  8. 【Spring学习笔记-MVC-12】Spring MVC视图解析器之ResourceBundleViewResolver

    场景 当我们设计程序界面的时候,中国人希望界面是中文,而美国人希望界面是英文. 我们当然希望后台代码不需改变,系统能够通过配置文件配置,来自己觉得是显示中文界面还是英文界面. 这是,Spring mv ...

  9. Spring学习笔记 7.1 Spring MVC起步

    7.1.1 跟踪Spring MVC的请求请求首先到达DispatcherServlet(DispatcherServlet是Spring MVC中的前端控制器):DispatcherServlet的 ...

随机推荐

  1. SGU 110. Dungeon 计算几何 难度:3

    110. Dungeon time limit per test: 0.25 sec. memory limit per test: 4096 KB The mission of space expl ...

  2. 玩转X-CTR100 l STM32F4 l DRV8825 A4988 步进电机控制

    我造轮子,你造车,创客一起造起来!塔克创新资讯[塔克社区 www.xtark.cn ][塔克博客 www.cnblogs.com/xtark/ ]      本文介绍X-CTR100控制器控制步进电机 ...

  3. html头标签meta实现refresh重定向

    <html> <head> <meta http-equiv="content-type" content="text/html; char ...

  4. Objective-C 类别(category)和扩展(Extension)

    1.类别(category) 使用Object-C中的分类,是一种编译时的手段,允许我们通过给一个类添加方法来扩充它(但是通过category不能添加新的实例变量),并且我们不需要访问类中的代码就可以 ...

  5. UI基础:UIButton.UIimage 分类: iOS学习-UI 2015-07-01 21:39 85人阅读 评论(0) 收藏

    UIButton是ios中用来响应用户点击事件的控件.继承自UIControl 1.创建控件 UIButton *button=[UIButton buttonWithType:UIButtonTyp ...

  6. 图片和span水平垂直居中

    <style type="text/css"> .content{ width:20%; height:60px; border:1px solid red; text ...

  7. [LeetCode&Python] Problem 559. Maximum Depth of N-ary Tree

    Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longe ...

  8. CF1092(div3):Great Vova Wall (栈)(还不错)

    D1. Great Vova Wall (Version 1): 题意:给定长度为N的墙,以及每个位置的一些高度,现在让你用1*2的砖和2*1的砖去铺,问最后能否铺到高度一样. 思路:分析其奇偶性,在 ...

  9. (dfs痕迹清理兄弟篇)bfs作用效果的后效性

    dfs通过递归将每种情景分割在不同的时空,但需要对每种情况对后续时空造成的痕迹进行清理(这是对全局变量而言的,对形式变量不需要清理(因为已经被分割在不同时空)) bfs由于不是利用递归则不能分割不同的 ...

  10. Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket

    https://blog.csdn.net/a123demi/article/details/78234023  : Springboot集成mybatis(mysql),mail,mongodb,c ...