SpringMVC10数据验证
在之前的案例上面! 引入需要的验证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数据验证的更多相关文章
- 我这么玩Web Api(二):数据验证,全局数据验证与单元测试
目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试 一.模型状态 - ModelState 我理解 ...
- MVC 数据验证
MVC 数据验证 前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解.System.ComponentModel.DataAnnotations 一.基础特性 一.Required 必填 ...
- kpvalidate开辟验证组件,通用Java Web请求服务器端数据验证组件
小菜利用工作之余编写了一款Java小插件,主要是用来验证Web请求的数据,是在服务器端进行验证,不是简单的浏览器端验证. 小菜编写的仅仅是一款非常初级的组件而已,但小菜为它写了详细的说明文档. 简单介 ...
- MVC3 数据验证用法之密码验证设计思路
描述:MVC数据验证使用小结 内容:display,Required,stringLength,Remote,compare,RegularExpression 本人最近在公司用mvc做了一个修改密码 ...
- jQuery MiniUI开发系列之:数据验证
在开发应用系统界面时,往往需要进行很多.复杂的数据验证,当填写的数据符合规定,才能提交保存. jQuery MiniUI提供了比较完美的表单数据验证和错误显示的方式. 常见的表单控件,都有一个验证事件 ...
- AngularJS快速入门指南14:数据验证
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- atitit.数据验证--db数据库数据验证约束
atitit.数据验证--db数据库数据验证约束 1. 为了加强账户数据金额的安全性,需要增加验证字段..1 2. 创建帐户1 3. 更改账户2 4. ---code3 5. --fini4 1. 为 ...
- MVC数据验证原理及自定义ModelValidatorProvider实现无编译修改验证规则和错误信息
Asp.net MVC中的提供非常简单易用的数据验证解决方案. 通过System.ComponentModel.DataAnnotations提供的很多的验证规则(Required, StringLe ...
- MVC 数据验证[转]
前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解. 一.基础特性 一.Required 必填选项,当提交的表单缺少该值就引发验证错误. 二.StringLength 指定允许的长度 指 ...
随机推荐
- C#.NET快速开发框架-企业版V4.0截图打包下载
C/S系统开发框架-企业版 V4.0 (Enterprise Edition) http://www.csframework.com/cs-framework-4.0.htm 其它图片打包下载: ht ...
- openshif ssh proxy
最近google又被墙了.没办法 1:注册一个openshift账号.申请注册一个app,获取一个免费主机. https://www.openshift.com/ 2:去PuTTY官方网站下载pL ...
- Python 异常处理--raise函数用法
raise语句手工引发一个异常: "raise" [expression ["," expression ["," expression]] ...
- [r]Ubuntu Linux系统下apt-get命令详解
Ubuntu Linux系统下apt-get命令详解(via|via) 常用的APT命令参数: apt-cache search package 搜索包 apt-cache show package ...
- 开发Nginx模块
开发Nginx模块 前面的哪些话 关于Nginx模块开发的博客资料,网上很多,很多.但是,每篇博客都只提要点,无法"step by step"照着做,对于初次接触Nginx开发的同 ...
- iOS判断手机中是否 有 SIM卡---备用
[CTSIMSupportGetSIMStatus() isEqualToString:kCTSIMSupportSIMStatusNotInserted]可以判断是否插入了sim卡. 前提是把下面的 ...
- 在Eclipse中安装m2e插件遇到的问题
最近自己想使用maven来搭建自动化测试框架,当中遇到了很多问题,其中之一就是安装m2e(Maven Integration for Eclipse). 其实原来的eclipse中已经安装好了m2e, ...
- Java中接口与实例化
一.问题引入 前两天学代理模式的时候想到的,接口可不可以new呢? 接口是特殊的抽象类,接口的方法都默认为 public abstract 的... 抽象的方法不 ...
- Unity3d ngui基础教程
Unity3d ngui基础教程 NGUI教程:步骤1-Scene 1.创建一个新的场景(New Scene).2.选择并删除场景里的MainCamera.3.在NGUI菜单下选择Create a N ...
- 在kafka上对topic新增partition
对topic增加partition 参考官网site:http://kafka.apache.org/documentation.html#basic_ops_modify_topic 通过kafka ...