林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka
服务器端的数据验证,对于一个WEB应用来说是非常重要的,而Spring从3.0开始支持JSR-303规范,它定义了一些标准的验证约束,同时也提供了一个可扩展的自定义方式来满足不同的开发需要,大象以SSM3为基础,结合实例来说明如何通过Spring MVC用自定义约束注解的方式来实现Validator验证。
validation-api是JSR-303规范的标准接口,hibernate-validator则是这套接口的一个实现,而hibernate-validator的实现里面又会用到slf4j,所以还需要加上这两个jar包。有了这些,我们就可以在此基础上实现自定义注解约束扩展了。
本文工程免费下载
一、在eclipse创建web项目
整个工程目录如下:
导入包
2、创建User类
并标注注解
其中@Length、@Email就是 Hibernate-validator中的数据校验注解,还可以用 javax.validation中的注解,比如@NotNull
package com.mucfc.model; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; /** *用户格式验证类 *@author linbingwen *@2015年5月17日15:45:27 */ public class User { @NotEmpty(message="用户名不能为空") private String userName; @NotEmpty(message="密码不能为空") @Length(min=6,max=16,message="密码长度不正确,得在6-16之间") private String userPassword; @NotEmpty(message="邮箱不能为空") @Email(message="邮箱格式不正确") private String userEmail; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- SpringMVC的前端控制器 --> <servlet> <servlet-name>MyDispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 加载配置文件路径 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </init-param> <!-- 何时启动 大于0的值表示容器启动时初始化此servlet,正值越小优先级越高 --> <load-on-startup>1</load-on-startup> </servlet> <!-- Spring MVC配置文件结束 --> <!-- SpringMVC拦截设置 --> <servlet-mapping> <servlet-name>MyDispatcher</servlet-name> <!-- 由SpringMVC拦截所有请求 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- SpringMVC拦截设置结束 --> <!--解决中文乱码问题 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
在Spring MVC配置文件中添加配置:
添加以下mvc的注解驱动配置,一切变成“自动化”
<mvc:annotation-driven />
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <mvc:annotation-driven/> <!-- 把标记了@Controller注解的类转换为bean --> <context:component-scan base-package="com.mucfc" /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp" /> </beans>
首先,要在需要进行校验的Bean前面加上@Valid注解,告诉SpringMVC框架这个Bean需要进行校验;同时,还要在需要校验的Bean前面加上@ModelAttribute注解,从而将Bean暴露给视图,并且指定名字,这有两个作用,第一是显示校验错误需要使用这个名字,第二个是返回原来的页面以后,前面输入的所有值还要显示出来;
其次,每个需要校验的Bean后面紧跟一个BindingResult,SpringMVC框架会将校验结果保存在它里面,通过hasErrors方法可以判断是否有校验错误;
最后,当返回到原页面以后,SpringMVC框架还会将所有校验错误信息保存在上下文中,供页面上取得校验错误,Spring提供了一套JSP自定义标签。
package com.mucfc.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.mucfc.model.User; @Controller public class UserControllers { @RequestMapping(value = "/register", method = {RequestMethod.POST}) public String registerCheck(Model model, @Valid @ModelAttribute("user")User user, BindingResult result) { if (result.hasErrors()) return "register"; else{ model.addAttribute("userName", user.getUserName()); return "forward:/success"; } } @ModelAttribute("user") public User getUser(){ User user=new User(); return user; } @RequestMapping(value = "/register", method = {RequestMethod.GET}) public String register() { return "register"; } @RequestMapping(value = "/success") public String success(HttpServletRequest request,HttpServletResponse response) { String str=(String)request.getAttribute("userName"); if(str==null||str.equals("")){ return "redirect:/register"; } return "success"; } }
(1)首先是用户数据输入register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>用户信息注册页面</title> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <center> <h1>注册新用户</h1> <form:form action="register" method="post" modelAttribute="user"> <form:errors path="*"></form:errors><br/><br/> <tr> <td><form:label path="userName">用户名:</form:label></td> <td><form:input path="userName"/></td><br/> <td><form:errors path="userName"/></td><br/> </tr><br/> <tr> <td><form:label path="userPassword">密 码: </form:label></td> <td><form:password path="userPassword"/></td><br/> <td><form:errors path="userPassword"/></td><br/> </tr><br/> <tr> <td><form:label path="userEmail">邮 箱: </form:label></td> <td><form:input path="userEmail"/></td><br/> <td><form:errors path="userEmail"/></td><br/> </tr><br/> <tr> <td colspan="3"><input type="submit" value="提交"></td> <td colspan="3"><input type="reset" value="重置"></td> </tr> </form:form> </center> </body> </html>这里用了SpringMVC的form表单,自动将输入和User注解格式类关联起来,当你输入正确的格式后,才会跳转到其它也页面,否则会要本页面报错误
在JSP页面上显示校验错误信息:
页面头部需要导入Spring的自定义标签库:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
需要一次性显示全部校验错误:
(commandName的值就是@ModelAttribute注解中指定的值)
<form:form commandName="userDetail"> <form:errors path="*" cssStyle="color:red"></form:errors> </form:form>
需要在对应输入框的后面显示单个校验错误:
(通过path指定显示那个具体的校验错误,userDetail正是@ModelAttribute注解中指定的值,点后面的是指定显示Bean中哪个属性的校验错误)
<input type="text" name="userName" value="${userDetail.userName}" > <form:errors path="userDetail.userName" cssStyle="color:red"></form:errors> <input type="text" name="email" value="${userDetail.email}"> <form:errors path="userDetail.email" cssStyle="color:red"></form:errors>
(2)用户注册信息正确提交后success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>用户信息注册页面</title> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <center> <h1>用户注册成功</h1><br/> 欢迎新用户:${userName} </center> </body> </html>
浏览器中输入:http://localhost:8080/SpringMVCLearningChapter3/register
进入注册页面
如果什么都不写直接提交,会报出如下错误
密码和邮箱格式出错
如果 数据格式都正确,刚会出现如下内容
二、注解说明
最后,再加一些注解说明