数据校验分为客户端校验和服务器端校验,客户端主要是经过过滤正经常使用户的误操做,是第一道防线,通常使用JavaScript代码实现。可是只有客户端校验是不够的,攻击者能够绕过客户端验证直接进行非法输入,这样可能会引发系统异常,为了确保数据的合法性,防止用户经过非正常手段提交错误信息,必须加上服务器端验证。
服务器端校验是整个应用阻止非法数据的最后一道防线,经过应用中的编程实现。服务器端验证对于系统的安全性、完整性、健壮性起到了相当重要的做用。在Spring MVC 框架中能够利用Spring自带的验证框架验证数据,也能够利用JSR303实现数据验证。
在Spring MVC 框架中有两种方法能够验证输入数据,一种是利用Spring自带的验证框架,另外一种是利用JSR303实现验证,推荐使用JSR303验证。html
对于JSR303验证,目前有两个实现,一个是Hibernate Validator,一个是Apache BVal。本教程采用的是Hibernate Validator,它和Hibernate无关,只是使用它进行数据验证。java
下载地址:https://sourceforge.net/projects/hibernate/files/hibernate-validator/
本教程使用的是hibernate-validator-5.4.0.Final-dist.zip
分别导入如下jar包:
dist目录下的 hibernate-validator-t.4.0.Final.jargit
dist/lib/required目录下的 classmate-1.3.1.jar、javax.el-3.0.1-b08.jar、jboss-logging-3.3.0.Final.jar、validation-api-1.1.0.Final.jarweb
在pom.xml中引入正则表达式
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.0.Final</version> </dependency>
在springmvc.xml配置文件中,注册校验器spring
<?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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!--将AnnotationHandler自动扫描到IOC容器中--> <context:component-scan base-package="com.springmvc"></context:component-scan> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置前缀--> <property name="prefix" value="/"></property> <!--配置后缀--> <property name="suffix" value=".jsp"></property> </bean> <!--注册校验器--> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> </bean> <!--开启Valid功能--> <mvc:annotation-driven validator="validator"></mvc:annotation-driven> </beans>
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Pattern; public class User {
@NotEmpty(message = "用户名不能为空") @Length(min = 6,max = 12,message = "用户名的长度为{min}-{max}位") private String username;
@NotEmpty(message = "密码不能为空") @Length(min = 6,max = 8,message = "密码的长度为{min}-{max}位") private String password;
@NotEmpty(message = "手机号不能为空") @Pattern(regexp = "^1[34578]\\d{9}$",message = "手机号格式不正确") private String phone; //getter和setter方法 }
@Controller public class ValidatorTestController { @RequestMapping("/userLogin") public String login(@Valid User user, BindingResult br, Model model){ int errorCount = br.getErrorCount(); if(errorCount>0){ FieldError username = br.getFieldError("username"); FieldError password = br.getFieldError("password"); FieldError phone = br.getFieldError("phone"); if (username!=null) { model.addAttribute("userNameMSG",username.getDefaultMessage()); } if (password!=null) { model.addAttribute("pwdMSG",password.getDefaultMessage()); } if (phone!=null) { model.addAttribute("phoneMSG",phone.getDefaultMessage()); } return "testValidator"; } return "success"; } }
建立testValid.jsp页面编程
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>数据校验</title> <style> span{ color: red;} </style> </head> <body> <form action="${pageContext.request.contextPath}/userLoginDemo" method="post"> <p> 用户名:<input type="text" name="username" value="${user.username}"> <span>${userNameMSG}</span> </p> <p> 密码:<input type="password" name="password" value="${user.password}"> <span>${pwdMSG}</span> </p> <p> 手机号:<input type="text" name="phone" value="${user.phone}"> <span>${phoneMSG}</span> </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>
效果展现:api
建议使用在Stirng,Integer类型,不建议使用在int类型上,由于表单值为“”时没法转换为int,但能够转换为Stirng为"",Integer为null数组