数据校验框架

(参考:http://blog.csdn.net/sinat_39955521/article/details/78922814

http://blog.csdn.net/sinat_39955521/article/details/78922427)

数据校验框架

Spring 3.0拥有直接独立的数据校验框架,同时支持JSR 303标准的校验框架,spring的DataBinder在进行数据绑定时,可以同时调用校验框架完成数据校验工作。在Spring MVC中,则可以直接通过注解驱动的方式进行数据校验。

Spring的org.springframework.validation是校验框架所在的包。

JSR 303

JSP 303是java为Bean数据合法性校验所提供的标准框架,它已经包含在java EE 6.0。JSR 303通过Bean属性上标注类似于@NotNull、@Max等标准的注解指定校验规则,并通过标准的验证接口对Bean进行验证。

你可以通过http://jcp.org/en/jsr/detail?id=3030了解JSP 303 的详细内容。


数据校验框架

<mvc:annotation-driven/>会默认装配好一个LocalValidatorFactoryBean,通过在处理方法的入参上标注@Valid注解既可让Spring MVC在完成数据绑定后执行数据校验的工作

public class User {   
      @Pattern(regexp="w{4,30}")
      private String userName;
	
      @Length(min=2,max=100)
      private String realName;
	
     @Past 
     @DateTimeFormat(pattern="yyyy-MM-dd")
     private Date birthday;
	
    @DecimalMin(value="1000.00")
    @DecimalMax(value="100000.00") 
    @NumberFormat(pattern="#,###.##")
    private long salary;
}

注意:Spring本身没有提供JSR 303的实现,所以必须将JSR 303的实现者(如Hibernate Validator)的jar文件放到类路径下,Spring将自动加载并装配好JSR 303的实现者。

如何使用注解驱动的校验

@Controller
public class UserController {
     @RequestMapping(value = "/handle91")
     public String handle91(@Valid  User user,BindingResult bindingResult){		
          if(bindingResult.hasErrors()){
               return "/user/register3";
          }else{
               return "/user/showUser";
          }
    }
在已经标注了JSR 303注解的表单/命令对象前标注一个@Valid,Spring MVC框架在将请求数据绑定到该入参对象后,就会调用校验框架根据注解声明的校验规则实施校验。
使用校验功能时,处理方法要如何签名?


       Spring MVC是通过对处理方法签名的规约来保存校验结果的:前一个表单/命令对象的校验结果保存在其后的入参中,这个保存校验结果的入参必须是BindingResult或Errors类型,这两个类都位于org.springframework.validation包中。

校验错误消息存放位置


4.Spring将HttpServletRequest对象数据绑定到处理方法的入参对象中(表单/命令对象);

5.将绑定错误消息、检验错误消息都保存到隐含模型中;

6.本次请求的对应隐含模型数据存放到HttpServletRequest的属性列表中,暴露给视图对象。

页面如何显示错误消息

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"      uri="http://java.sun.com/jsp/jstl/core" %>   
<%@ taglib prefix="form"   uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>注册用户</title>
  <style>.errorClass{color:red}</style>
</head>
<body> 
  <form:form modelAttribute="user"  action="user/handle91.html">
      <form:errors path="*"/>
      <table>
	    <tr>
	       <td>用户名:</td>
	       <td>
	          <form:errors path="userName" cssClass="errorClass"/>
	          <form:input path="userName" />
	       </td>
	    </tr>
           …	    
    </table>
  </form:form>
</body>
</html>
示例:

所需jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.et</groupId>
  <artifactId>SpringMvc_Verify</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name/>
   <dependencies>
    <!-- springmvc依赖 -->
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>4.2.0.RELEASE</version>
  	</dependency>
    <!--jsr303验证框架 -->
	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-validator</artifactId>
	    <version>4.3.2.Final</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
	<dependency>
		<groupId>net.sf.json-lib</groupId>
		<artifactId>json-lib</artifactId>
		<version>2.4</version>
		<classifier>jdk15</classifier>
	</dependency>
	<!-- 添加jackson的json解析器 -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.8.9</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>
	
	
    <dependency>
      <groupId>org.apache.openejb</groupId>
      <artifactId>javaee-api</artifactId>
      <version>5.0-1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.faces</groupId>
      <artifactId>jsf-api</artifactId>
      <version>1.2_04</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.faces</groupId>
      <artifactId>jsf-impl</artifactId>
      <version>1.2_04</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>${basedir}/src</sourceDirectory>
    <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
    <resources>
      <resource>
        <directory>${basedir}/src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <webappDirectory>${basedir}/WebRoot</webappDirectory>
          <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<!-- 在使用springmvc的标签或者国际化中 都需要spring的支持  指定spring配置文件位置-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  <!-- 请求method支持put和delete必须添加过滤器 -->
	<filter>
		<filter-name>myFile</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>myFile</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 
		解决乱码的配置    使用拦截器拦截/*所有路径,将请求头和响应头都设置为UTF-8
	-->
<filter>
	<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<!-- 设置request 字符集 -->
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
	<init-param>
		<!-- 设置response 字符集 -->
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>encodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
  
  
   <!-- 配置springmvc的核心控制器  将uri拦截下来 -->
	<servlet>
		<servlet-name>mvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
springmvc.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
	">
  <!-- 指定扫描的位置 -->  
  <context:component-scan base-package="cn"></context:component-scan>
   <!-- springmvc 配置拦截  / 所有资源都被拦截 图片无法展示  将除控制层以外的资源交回给servlet处理 -->
    <mvc:default-servlet-handler/>
    <!-- 将springmvc注解的action交给springmvc处理 -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>
spring,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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	">
	
</beans>
校验类

package cn.et;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;


public class UserInfo {
	/**
	 * NotNull 属性名 !=null
	 * NotEmpty 属性名!=null &&  !属性名.equals("")
	 */
	@NotEmpty(message="用户名不能为空")
	private String userName;
	
	@NotEmpty(message="密码不能为空")
	private String password;
	
	@NotEmpty(message="再次输入不能为空")
	private String repassword;
	
	// lixin@126.com  
	@Pattern(message="邮箱格式错误",regexp=".+@.+\\..+")
	private String email;
	
	@NotEmpty(message="年龄不能为空")
	@Min(value=1,message="年龄必须大于1")
	@Max(value=100,message="年龄必须小于100")
	private String age;
	
	@Size(min=11, max=11,message="手机号码必须是11位")
	private String phone;
	
	@Pattern(message="时间格式错误",regexp="(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)")
	private String time;
	
	@Pattern(message="网址格式错误",regexp="^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$")
	private String url;
	
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time = time;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	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;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}


持久层

package cn.et;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 后台验证步骤
 * 	1.javabean添加验证注解
 * 	2.action中使用@Valid表示javabean 使用Errors或者BindingResult判断是否验证失败
 *  3.出现jar包冲突4.3.2
 *  
 * @author Administrator
 *
 */
@Controller
public class RegController {
	@RequestMapping(value="/reg",method=RequestMethod.POST)
	public String reg(@ModelAttribute("user") @Valid UserInfo user,BindingResult errors){
		//用于判断密码是否一致
		if(!user.getPassword().equals(user.getRepassword())){
			errors.addError(new FieldError("userInfo","repassword","两次密码不一致"));
		}
		if(errors.hasErrors()){																			
			return "/reg.jsp";
		}
		return "/suc.jsp";
	}
}
reg.jsp显示界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'MyJsp.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">
	-->
	<script type="text/javascript">
  		function checkSubmit(){
  			//获取用户名并判断是否为空
  			var userName=document.getElementsByName("userName")[0].value;
  			if(userName==null || userName==""){
  				alert("用户名不能为空");
  				return;
  			}
  			//获取密码并判断是否为空
  			var password=document.getElementsByName("password")[0].value;
  			if(password==null || password==""){
  				alert("密码不能为空");
  				return;
  			}
  			//获取再次输入的密码并判断是否为空
  			var repassword=document.getElementsByName("repassword")[0].value;
  			if(repassword==null || repassword==""){
  				alert("重复密码不能为空");
  				return;
  			}
  			if(password!=repassword){
  				alert("两次输入密码不一致");
  				return;
  			}
  			//提交
  			document.forms[0].submit();
  		}
  	</script>
  </head>

  <body>
	  <form action="<%=path%>/reg" method="post">
			用户名:<input type="text" name="userName" />
			<!-- 将校验消息显示出来(如果没有错误就不显示)-->
			<font color="red"><form:errors path="user.userName"></form:errors></font>
			<br/>
			密码:<input type="password" name="password" />
			<font color="red"><form:errors path="user.password"></form:errors></font>
			<br/>
			重复密码:<input type="password" name="repassword" />
			<font color="red"><form:errors path="user.repassword"></form:errors></font>
			<br/>
			邮件:<input type="text" name="email" />
			<font color="red"><form:errors path="user.email"></form:errors></font>
			<br/>
			年龄:<input type="text" name="age" />
			<font color="red"><form:errors path="user.age"></form:errors></font>
			<br/>
			手机号码:<input type="text" name="phone" />
			<font color="red"><form:errors path="user.phone"></form:errors></font>
			<br/>
			<!-- 时间  输入格式 yyyy-MM-dd -->
			时间:<input type="text" name="time" >
			<font color="red"><form:errors path="user.time"></form:errors></font>
			<br/>
			<!-- 网址 http://www.baidu.com http://ip:端口/ -->
			个人网址:<input type="text" name="url" >
			<font color="red"><form:errors path="user.url"></form:errors></font>
			<br/>
			<input type="button" value="提交" οnclick="checkSubmit()">
		</form>
  </body>
</html>






  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值