springMVC数据校验
在web应用程序中,为了防止客户端传来的数据引发程序异常,常常需要对 数据进行验证。输入验证分为客户端验证与服务器端验证。客户端验证主要通过JavaScript脚本进行,而服务器端验证则主要通过Java代码进行验证。
为了保证数据的安全性,一般情况下,客户端和服务器端验证都是必须的
1.导入jar包
SpringMVC支持JSR(Java Specification Result,Java规范提案)303-Bean Validation数据验证规范。而该规范的实现者很多,其中较常用的是Hibernate Validator。需要注意的是,Hibernate Validator是与Hibernate ORM并列的Hibernate的产品之一。这一点从Hibernate官网上所提供的资源形式可以看出他们之间的关系。
hibernate-validator-4.3.1.Final.jar、jboss-logging-3.3.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中
2.在applicationContext.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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 配置包扫描器--> <context:component-scan base-package="cn.controller"></context:component-scan> <!-- 配置验证器 --> <bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> </bean> <mvc:annotation-driven validator="myvalidator"/> </beans>
3.定义实体类,打注解标记
package cn.entity; 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 { //必须是0到100之间 @Min(value=0,message="成绩最小值为{value}") @Max(value=100,message="成绩最大值为{value}") private Integer score; //手机号码必须不能为空,必须是以1 开头 第二位3,4,5,6,7,8,9 最后9位随意 @NotEmpty(message="手机号码不允许为空") @Pattern(regexp="^1[3,4,5,6,7,8,9]\\d{9}$",message="手机号码不正确") private String phone; //不能为空 //必须是6个字符以上 @NotEmpty(message="用户名不能为空") @Size(min=6,message="名称至少6个字符") private String name; public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
4.在我们的处理器类中进行相应的判断处理
package cn.controller; 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.RequestMapping; import org.springframework.web.servlet.ModelAndView; import cn.entity.UserInfo; @Controller public class FirstController { @RequestMapping("/first.do") public ModelAndView doFirst(@Valid UserInfo info,BindingResult br){ ModelAndView mv=new ModelAndView(); mv.setViewName("/welcome.jsp"); int errorCount = br.getErrorCount(); if (errorCount>0) { FieldError score = br.getFieldError("score"); FieldError name = br.getFieldError("name"); FieldError phone = br.getFieldError("phone"); if (score!=null) { mv.addObject("scoremsg",score.getDefaultMessage()); } if (name!=null) { mv.addObject("namemsg",name.getDefaultMessage()); } if (phone!=null) { mv.addObject("phonemsg",phone.getDefaultMessage()); } mv.setViewName("/index.jsp"); } return mv ; } }
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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title></title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> </head> <body> <h1>数据校验</h1> <form action="${pageContext.request.contextPath }/first.do" method="post"> 成绩:<input name="score" /> <span>${scoremsg }</span><br/><br/> 姓名:<input name="name"/><span>${namemsg }</span><br/><br/> 电话:<input name="phone"/><span>${phonemsg }</span><br/><br/> <input type="submit" value="注册"/> </form> </body> </html>