在之前的案例上面! 引入需要的验证jar包

创建index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<form action="student/addStudent" method="post">
年龄:<input type="text" name="age"/> ${ageE} <br/>
姓名: <input type="text" name="userName"/>${userNameE}<br/>
电话:<input type="text" name="phone"> ${phoneE}<br/>
<input type="submit" value="新增"/>
</form>
</body>
</html>

对应的Student类

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; /**
*
* @NotNull 作用在基本数据类型上
* @NotBlank 作用在String上
* @NotEmpty 作用在集合上
* @Min 最小值
* @Max 最大值
* @Size 字符串的长度
* @Pattern 自定义验证规则
*
*/
public class Student { @NotNull(message="年龄不能为空")
@Min(value=0,message="年龄不能低于{value}")
@Max(value=150,message="年龄不能高于{value}")
private Integer age; //年龄
@NotBlank(message="姓名不能为空")
@Size(min=6,max=10,message="长度必须在{min}---{max}之间")
private String userName; //姓名
@NotBlank(message="手机号不能为空")
@Pattern(regexp="^1[345789]\\d{9}$",message="手机格式不正确")
private String phone; //电话 public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Student(Integer age, String userName, String phone) {
super();
this.age = age;
this.userName = userName;
this.phone = phone;
}
public Student() {
super();
} }

对应的controller

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import sun.util.calendar.BaseCalendar; import cn.bdqn.bean.Student; @Controller
@RequestMapping("/student")
public class StudentController { /**
*
*@Validated :会对student对象中所有标注 注解的属性进行验证!
*BindingResult:如果 验证出现错误 ,就会把错误信息给这个result
*
*result.getFieldError("age").getDefaultMessage()
*获取我们设置的错误 信息!
*
*/
@RequestMapping("/addStudent")
public ModelAndView addStudent(@Validated Student student,BindingResult result) {
System.out.println("进入了 addStudent");
ModelAndView mv=new ModelAndView();
if (result.hasErrors()) { //出现了验证错误
if (result.getFieldError("age")!=null) { //证明age验证有错误
mv.addObject("ageE", result.getFieldError("age").getDefaultMessage());
}
if (result.getFieldError("userName")!=null) { //证明userName验证有错误
mv.addObject("userNameE", result.getFieldError("userName").getDefaultMessage());
}
if (result.getFieldError("phone")!=null) { //证明phone验证有错误
mv.addObject("phoneE", result.getFieldError("phone").getDefaultMessage());
}
mv.setViewName("/index.jsp");
return mv;
}
mv.setViewName("/success.jsp");
return mv;
} }

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 配置springmvc的组件 -->
<context:component-scan base-package="cn.bdqn.controller"/>
<!-- 开启 注解的方式-->
<mvc:annotation-driven validator="myValidator"/>
<!-- 生成我们的验证器 -->
<bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean> </beans>

SpringMVC10数据验证的更多相关文章

  1. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

  2. MVC 数据验证

    MVC 数据验证 前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解.System.ComponentModel.DataAnnotations 一.基础特性 一.Required 必填 ...

  3. kpvalidate开辟验证组件,通用Java Web请求服务器端数据验证组件

    小菜利用工作之余编写了一款Java小插件,主要是用来验证Web请求的数据,是在服务器端进行验证,不是简单的浏览器端验证. 小菜编写的仅仅是一款非常初级的组件而已,但小菜为它写了详细的说明文档. 简单介 ...

  4. MVC3 数据验证用法之密码验证设计思路

    描述:MVC数据验证使用小结 内容:display,Required,stringLength,Remote,compare,RegularExpression 本人最近在公司用mvc做了一个修改密码 ...

  5. jQuery MiniUI开发系列之:数据验证

    在开发应用系统界面时,往往需要进行很多.复杂的数据验证,当填写的数据符合规定,才能提交保存. jQuery MiniUI提供了比较完美的表单数据验证和错误显示的方式. 常见的表单控件,都有一个验证事件 ...

  6. AngularJS快速入门指南14:数据验证

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  7. atitit.数据验证--db数据库数据验证约束

    atitit.数据验证--db数据库数据验证约束 1. 为了加强账户数据金额的安全性,需要增加验证字段..1 2. 创建帐户1 3. 更改账户2 4. ---code3 5. --fini4 1. 为 ...

  8. MVC数据验证原理及自定义ModelValidatorProvider实现无编译修改验证规则和错误信息

    Asp.net MVC中的提供非常简单易用的数据验证解决方案. 通过System.ComponentModel.DataAnnotations提供的很多的验证规则(Required, StringLe ...

  9. MVC 数据验证[转]

    前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解. 一.基础特性 一.Required 必填选项,当提交的表单缺少该值就引发验证错误. 二.StringLength 指定允许的长度 指 ...

随机推荐

  1. Android 之夜间模式(多主题)的实现

    引言 夜间模式其实属于多主题切换的一种,不过是最麻烦的一种.因为在夜间模式下不仅要切换主色调,次要色调等等,还要覆盖一些特殊的颜色,因为在夜间模式下总不能什么都是黑的把,那不得丑死-.-,所以当你夜间 ...

  2. iso 开发学习--简易音乐播放器(基于iPhone4s屏幕尺寸)

    三个按钮  一个进度条 贴图(软件中部分图片,来自网络,如果侵犯了您的权益,请联系我,会立刻撤下) 核心代码 // // ViewController.m // 08-10-MusicPlayer / ...

  3. 解决weblogic Managed Server启动非常慢的情况

    jdk版本:1.7.0_79 查看控制台日志停留在如下地方: . . JAVA Memory arguments: -Xms2048m -Xmx4096m -XX:MaxPermSize=512m . ...

  4. 【转】Any way to implement BLE notifications in Android-L preview----不错

    原文网址:http://stackoverflow.com/questions/24865120/any-way-to-implement-ble-notifications-in-android-l ...

  5. 黄源河《左偏树的应用》——数字序列(Baltic 2004)

    这道题哪里都找不到. [问题描述] 给定一个整数序列a1, a2, … , an,求一个不下降序列b1 ≤ b2 ≤ … ≤ bn,使得数列{ai}和{bi}的各项之差的绝对值之和 |a1 - b1| ...

  6. IOS的 testflight测试设置

    管理员邀请参与者 1.登录开发者账号https://developer.apple.com/account 2.进入后,点击ituns connect 3.点击进入用户和职能 4.在用户栏点击添加按钮 ...

  7. QTP自传之测试报告

    前言 测试报告是测试阶段的最后产出,也是最重要的产出,自动化测试报告也是如此.前期所做的工作,添加对象.编写脚本等都是为了可以生成一份正确.严谨的测试报告.我作为一款功能全面的自动化测试工具,毫无疑问 ...

  8. java工作流bpm开发ERP实例

    今天看了一个java工作流bpm开发ERP的例子,文章介绍:http://tech.it168.com/a2009/0507/275/000000275294_14.shtml 增加数据块 一路照做就 ...

  9. 服务器之间免密码ssh登陆

    配置服务器f1(192.168.1.1)与服务器f2(192.168.1.2)之间免密码ssh登陆 一.首先,配置服务器主机名为f1.f2 1.更改/etc/sysconfig下的network文件, ...

  10. Vagrant网络配置

    Vagrant中网络配置 一.基本配置 Vagrant offers multiple options for how you are able to connect your guest machi ...