Spring MVC 验证主要还是用的是hibernate的验证。so需要添加以下的jar包:

1、 hibernate-validator-5.2.2.Final.jar

2、hibernate-validator-annotation-processor-5.2.2.Final.jar (这个可以不用)

3、 log4j.jar

4 、slf4j-api-1.5.6.jar

5、 slf4j-log4j12-1.5.6.jar

6 、validation-api-1.1.0.Final.jar

以登录验证为例:

在实体属性上配置注解;

package com.cy.springannotation.entity;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty; /**
* 定义一个表单实体类
* @author acer
*
*/
public class UserBean {
//要求属性名必须要和表单的参数名一样的! @NotEmpty(message="用户名不能为空!")
@Pattern(regexp="\\w{6,20}",message="用户名6-20位")
private String username; @NotEmpty(message="密码不能为空")
@Length(max=20,min=6,message="密码不能小于6位")
private String password; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }

JSP页面上通过spring标记来获取错误信息:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!-- srpingmvc 验证需要使用到spring表单标签 -->
<%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>验证页面</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> <!-- commandName用于指定活动的Bean对象,即我可以在页面上,获取对象属性所对应的错误信息,值是对象名称的首字母小写,同modelAttribute一样的意思(modelAttribute="contentModel") -->
<!-- <springform:form method="post" action="login.do" commandName="userBean"> -->
<springform:form method="post" action="login.do" modelAttribute="user"> <table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/><springform:errors delimiter="," path="username"></springform:errors></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="password"/><springform:errors delimiter="," path="password"></springform:errors></td>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="提交"/> </td>
</tr>
</table>
</springform:form>
</body>
</html>

delimiter:如果一个属性有多个错误,错误信息的分隔符。默认是换行.

path:验证失败的属性名.

控制器:

 @RequestMapping(value="/login.do")
//@Valid 通过该注解告知该方法,我的哪个实体Bean需要验证
//BindingResult 为固定参数,用于接收验证结果 public String login(@ModelAttribute("user") @Valid UserBean user,BindingResult br) {
if(br.hasErrors()){
//验证未通过则
return "validate1";
}
log.info(user.getUsername());
log.info(user.getPassword()); return "index";
}

如果界面上使用了spring标签,那么需要预先启动Spring容器,所以在web.xml中增加配置:

 <!-- 启动spring容器,用于支持springmvc validate -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/springAnnotation-servlet.xml</param-value>
</context-param> <!-- 配置在context-param里面文件内的内容,需要通过 ContextLoaderListener添加到上下文里面去-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

到springAnnotation-servlet.xml文件中配置:

 <!-- 开启注解这里需要添加个validator-->
<!--开启注解 -->
<mvc:annotation-driven conversion-service="tc" validator="validator" /> <!-- 验证配置,告知srpingmvc,我使用的是Hibernate验证框架来完成的验证 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
</bean>

显示测试:

进入登录页面

直接点击提交:

下面是主要的验证注解及说明:

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,CollectionMap and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

Spring MVC 之输入验证(六)的更多相关文章

  1. JSR-303 Bean Validation 介绍及 Spring MVC 服务端验证最佳实践

    任何时候,当要处理一个应用程序的业务逻辑,数据校验是你必须要考虑和面对的事情. 应用程序必须通过某种手段来确保输入参数在上下文来说是正确的. 分层的应用在很多时候,同样的数据验证逻辑会出现在不同的层, ...

  2. Spring MVC 学习总结(六)——Spring+Spring MVC+MyBatis框架集成

    与SSH(Struts/Spring/Hibernate/)一样,Spring+SpringMVC+MyBatis也有一个简称SSM,Spring实现业务对象管理,Spring MVC负责请求的转发和 ...

  3. Spring MVC 使用介绍(六)—— 注解式控制器(二):请求映射与参数绑定

    一.概述 注解式控制器支持: 请求的映射和限定 参数的自动绑定 参数的注解绑定 二.请求的映射和限定 http请求信息包含六部分信息: ①请求方法: ②URL: ③协议及版本: ④请求头信息(包括Co ...

  4. Spring MVC 表单验证

    1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constrain ...

  5. Spring MVC 响应视图(六)

    完整的项目案例: springmvc.zip 目录 实例 除了依赖spring-webmvc还需要依赖jackson-databind(用于转换json数据格式) <dependency> ...

  6. spring mvc @Valid 数据验证

    //对书的单价校验不能是空,价格在20-100之间   @DecimalMax(value = "100", message = "价格不超过100元")   ...

  7. [Spring MVC] - InitBinder验证

    Spring MVC使用InitBinder验证: 使用InitBinder做验证的情况一般会在此Controller中提交的数据需要有一些是业务性质的,也即比较复杂的验证情况下才会使用.大部份简单的 ...

  8. JSR-303 Bean Validation 介绍及 Spring MVC 服务端参数验证最佳实践

    任何时候,当要处理一个应用程序的业务逻辑,数据校验是你必须要考虑和面对的事情. 应用程序必须通过某种手段来确保输入参数在上下文来说是正确的. 分层的应用很多时候同样的数据验证逻辑会出现在不同的层,这样 ...

  9. [Spring MVC] - Annotation验证

    使用Spring MVC的Annotation验证可以直接对view model的简单数据验证,注意,这里是简单的,如果model的数据验证需要有一些比较复杂的业务逻辑性在里头,只是使用annotat ...

随机推荐

  1. 测试-ConstantForce的驱动方式以及是否穿透

    当我把FixedUpdate更新频率设置为1秒一次,测试结果如下: 结论: 1.由物理更新驱动 2.不会产生穿透

  2. nylg 小M的因子和

    小M的因子和 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 小M在上课时有些得意忘形,老师想出道题目难住他.小M听说是求因子和,还是非常得意,但是看完题目是求A的B ...

  3. dubbo子模块

    dubbo源码版本:2.5.4 经统计,dubbo一共有36个子模块,子模块如下: ---------------------------------------------------------- ...

  4. CSocket客户端(TCP)

    首先是UDP和TCP的区别: UDP是不连接服务器,每次发送数据的时候需要服务器的IP:而TCP是先连接服务器,保持常连接,然后直接发送不需要IP. 下面是TCP客户端: 1.新建项目,TestCSo ...

  5. VC++实现在系统托盘来新消息闪烁,鼠标悬停显示窗口

    转载:http://www.codeguru.com/cpp/com-tech/activex/tutorials/article.php/c8115/How-to-Implement-a-Mouse ...

  6. UVA10339 Watching Watches

    题目大意:有两个表,每天都会慢一点时间,给出每天慢得秒数,问下一次重合的时刻. 解题思路:时刻重合也就是说整整差了一周,一周是12小时,用12小时的秒数除以两个表的相差那就是需要多少天的时间后重合,知 ...

  7. Python3基础 print 中字符串乘以数字,重复输出多次

    镇场诗:---大梦谁觉,水月中建博客.百千磨难,才知世事无常.---今持佛语,技术无量愿学.愿尽所学,铸一良心博客.------------------------------------------ ...

  8. Linux下新的网络管理工具ip替代ifconfig零压力

    如果你使用 Linux 足够久,那么你自然知道一些工具的来与去.2009年 Debian 开发者邮件列表宣布放弃使用缺乏维护的 net-tools 工具包正是如此.到今天 net-tools 仍然被部 ...

  9. 【leetcode❤python】237. Delete Node in a Linked List

    #-*- coding: UTF-8 -*- # Definition for singly-linked list.# class ListNode(object):#     def __init ...

  10. FreeSWITCH第三方库(其他)的简单介绍(三)

    FreeSWITCH使用了大量的第三方库,本文档主要介绍关联相关库的信息: 音频相关库的信息介绍参考:http://www.cnblogs.com/yoyotl/p/5486753.html 视频相关 ...