当前位置: 首页 > news >正文

【Spring学习笔记-MVC-10】Spring MVC之数据校验

作者: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" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  12. <!-- 扫描web包,应用Spring的注解 -->
  13. <context:component-scan base-package="com.ll.web"/>
  14. <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面,默认优先级最低 -->
  15. <bean
  16. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  17. p:viewClass="org.springframework.web.servlet.view.JstlView"
  18. p:prefix="/jsp/"
  19. p:suffix=".jsp" />
  20. <!-- 设置数据校验、数据转换、数据格式化 -->
  21. <mvc:annotation-driven validator="validator" conversion-service="conversionService"/>
  22. <!-- 数据转换/数据格式化工厂bean -->
  23. <bean id="conversionService"
  24. class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
  25. <!-- 设置校验工厂bean-采用hibernate实现的校验jar进行校验-并设置国际化资源显示错误信息 -->
  26. <bean id="validator"
  27. class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  28. <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
  29. <!--不设置则默认为classpath下的 ValidationMessages.properties -->
  30. <property name="validationMessageSource" ref="validatemessageSource" />
  31. </bean>
  32. <!-- 设置国际化资源显示错误信息 -->
  33. <bean id="validatemessageSource"
  34. class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  35. <property name="basename">
  36. <list>
  37. <value>classpath:valideMessages</value>
  38. </list>
  39. </property>
  40. <property name="fileEncodings" value="utf-8" />
  41. <property name="cacheSeconds" value="120" />
  42. </bean>
  43. </beans>

3. 待校验的Java对象


   
  1. package com.ll.model;
  2. import java.util.Date;
  3. import javax.validation.constraints.DecimalMax;
  4. import javax.validation.constraints.DecimalMin;
  5. import javax.validation.constraints.Past;
  6. import javax.validation.constraints.Pattern;
  7. import org.hibernate.validator.constraints.Length;
  8. import org.springframework.format.annotation.DateTimeFormat;
  9. import org.springframework.format.annotation.NumberFormat;
  10. public class Person {
  11. @Pattern(regexp="W{4,30}",message="{Pattern.person.username}")
  12. private String username;
  13. @Pattern(regexp="S{6,30}",message="{Pattern.person.passwd}")
  14. private String passwd;
  15. @Length(min=2,max=100,message="{Pattern.person.passwd}")
  16. private String realName;
  17. @Past(message="{Past.person.birthday}")
  18. @DateTimeFormat(pattern="yyyy-MM-dd")
  19. private Date birthday;
  20. @DecimalMin(value="1000.00",message="{DecimalMin.person.salary}")
  21. @DecimalMax(value="2500.00",message="{DecimalMax.person.salary}")
  22. @NumberFormat(pattern="#,###.##")
  23. private long salary;
  24. public Person() {
  25. super();
  26. }
  27. public Person(String username, String passwd, String realName) {
  28. super();
  29. this.username = username;
  30. this.passwd = passwd;
  31. this.realName = realName;
  32. }
  33. public String getUsername() {
  34. return username;
  35. }
  36. public void setUsername(String username) {
  37. this.username = username;
  38. }
  39. public String getPasswd() {
  40. return passwd;
  41. }
  42. public void setPasswd(String passwd) {
  43. this.passwd = passwd;
  44. }
  45. public String getRealName() {
  46. return realName;
  47. }
  48. public void setRealName(String realName) {
  49. this.realName = realName;
  50. }
  51. public Date getBirthday() {
  52. // DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  53. // return df.format(birthday);
  54. return birthday;
  55. }
  56. public void setBirthday(Date birthday) {
  57. this.birthday = birthday;
  58. }
  59. public long getSalary() {
  60. return salary;
  61. }
  62. public void setSalary(long salary) {
  63. this.salary = salary;
  64. }
  65. @Override
  66. public String toString() {
  67. return "Person [username=" + username + ", passwd=" + passwd + "]";
  68. }
  69. }

4. 国际化资源文件



5. 控制层


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


   
  1. package com.ll.web;
  2. import java.security.NoSuchAlgorithmException;
  3. import javax.validation.Valid;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.validation.BindingResult;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import com.ll.model.Person;
  9. /**
  10. * @author Administrator
  11. *
  12. */
  13. @Controller
  14. @RequestMapping(value = "/test")
  15. public class TestController {
  16. @ModelAttribute("person")
  17. public Person initModelAttr() {
  18. Person person = new Person();
  19. return person;
  20. }
  21. /**
  22. * 返回主页
  23. * @return
  24. */
  25. @RequestMapping(value = "/index.action")
  26. public String index() {
  27. return "regedit";
  28. }
  29. /**
  30. * 1. 在入参对象前添加@Valid注解,同时在其后声明一个BindingResult的入参(必须紧随其后),
  31. * 入参可以包含多个BindingResult参数;
  32. * 2. 入参对象前添加@Valid注解:请求数据-->入参数据 ===>执行校验;
  33. * 3. 这里@Valid在Person对象前声明,只会校验Person p入参,不会校验其他入参;
  34. * 4. 概括起来:@Valid与BindingResult必须成对出现,且他们之间不允许声明其他入参;
  35. * @param bindingResult :可判断是否存在错误
  36. */
  37. @RequestMapping(value = "/FormattingTest")
  38. public String conversionTest(@Valid @ModelAttribute("person") Person p,
  39. BindingResult bindingResult) throws NoSuchAlgorithmException {
  40. // 输出信息
  41. System.out.println(p.getUsername() + " " + p.getPasswd() + " "
  42. + p.getRealName() + " " + " " + p.getBirthday() + " "
  43. + p.getSalary());
  44. // 判断校验结果
  45. if(bindingResult.hasErrors()){
  46. System.out.println("数据校验有误");
  47. return "regedit";
  48. }else {
  49. System.out.println("数据校验都正确");
  50. return "success";
  51. }
  52. }
  53. }

6. 前台

引入Spring的form标签:

在前台显示错误:



   
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  3. <html>
  4. <head>
  5. <title>数据校验</title>
  6. <style>
  7. .errorClass{color:red}
  8. </style>
  9. </head>
  10. <body>
  11. <form:form modelAttribute="person" action='FormattingTest.action' >
  12. <form:errors path="*" cssClass="errorClass" element="div"/>
  13. <table>
  14. <tr>
  15. <td>用户名:</td>
  16. <td>
  17. <form:errors path="username" cssClass="errorClass" element="div"/>
  18. <form:input path="username" />
  19. </td>
  20. </tr>
  21. <tr>
  22. <td>密码:</td>
  23. <td>
  24. <form:errors path="passwd" cssClass="errorClass" element="div"/>
  25. <form:password path="passwd" />
  26. </td>
  27. </tr>
  28. <tr>
  29. <td>真实名:</td>
  30. <td>
  31. <form:errors path="realName" cssClass="errorClass" element="div"/>
  32. <form:input path="realName" />
  33. </td>
  34. </tr>
  35. <tr>
  36. <td>生日:</td>
  37. <td>
  38. <form:errors path="birthday" cssClass="errorClass" element="div"/>
  39. <form:input path="birthday" />
  40. </td>
  41. </tr>
  42. <tr>
  43. <td>工资:</td>
  44. <td>
  45. <form:errors path="salary" cssClass="errorClass" element="div"/>
  46. <form:input path="salary" />
  47. </td>
  48. </tr>
  49. <tr>
  50. <td colspan="2"><input type="submit" name="提交"/></td>
  51. </tr>
  52. </table>
  53. </form:form>
  54. </body>
  55. </html>


7. 测试


输入:http://localhost:8080/SpringMVCTest/test/index.action 

8. 其他

参考链接:
http://www.cnblogs.com/ssslinppp 
http://blog.sina.com.cn/spstudy 
http://www.cnblogs.com/liukemng/p/3738055.html 
http://www.cnblogs.com/liukemng/p/3754211.html 
淘宝源程序下载(可直接运行):
http://shop110473970.taobao.com/?spm=a230r.7195193.1997079397.42.AvYpGW 
http://shop125186102.taobao.com/?spm=a1z10.1-c.0.0.SsuajD    






来自为知笔记(Wiz)


附件列表

 

相关文章:

  • 为什么使用MAVEN 3.2.1会有版本问题?
  • ng6--错误信息小结(持续更新)
  • org.tinygroup.context2object-参数对象构建
  • 思考 | 云计算 + 区块链 = ?
  • devexpress表格控件gridcontrol设置隔行变色、焦点行颜色、设置(改变)显示值、固定列不移动(附源码)...
  • Day 33 三剑客-awk
  • HDU 4828 (卡特兰数+逆)
  • python学习-文件处理
  • 四、oracle 用户管理二
  • 3.字典常用功能
  • java多线程下载
  • MySQLdb的安装与使用
  • 谋势、聚力、强生态,用友三十而立
  • linux下svn服务器搭建
  • 聊聊sentinel的AuthoritySlot
  • 【Amaple教程】5. 插件
  • 77. Combinations
  • - C#编程大幅提高OUTLOOK的邮件搜索能力!
  • CSS盒模型深入
  • ES6, React, Redux, Webpack写的一个爬 GitHub 的网页
  • Git同步原始仓库到Fork仓库中
  • Javascript弹出层-初探
  • overflow: hidden IE7无效
  • React Transition Group -- Transition 组件
  • Sass Day-01
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • vue学习系列(二)vue-cli
  • Vue组件定义
  • 搭建gitbook 和 访问权限认证
  • 仿天猫超市收藏抛物线动画工具库
  • 盘点那些不知名却常用的 Git 操作
  • 如何打造100亿SDK累计覆盖量的大数据系统
  • 三分钟教你同步 Visual Studio Code 设置
  • 设计模式 开闭原则
  • 实现简单的正则表达式引擎
  • 说说动画卡顿的解决方案
  • 思考 CSS 架构
  • 算法-图和图算法
  • 我建了一个叫Hello World的项目
  • 优秀架构师必须掌握的架构思维
  • 由插件封装引出的一丢丢思考
  • 责任链模式的两种实现
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • 从如何停掉 Promise 链说起
  • ​queue --- 一个同步的队列类​
  • ​如何使用ArcGIS Pro制作渐变河流效果
  • (Python) SOAP Web Service (HTTP POST)
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (算法)N皇后问题
  • (转)机器学习的数学基础(1)--Dirichlet分布
  • ***通过什么方式***网吧
  • .Family_物联网
  • .NET Core引入性能分析引导优化
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET/C# 反射的的性能数据,以及高性能开发建议(反射获取 Attribute 和反射调用方法)