1.spring4.0整合了validation驗(yàn)證功能
2.SpringMVC 使用驗(yàn)證框架 Bean Validation(上)
??對于任何一個(gè)應(yīng)用而言在客戶端做的數(shù)據(jù)有效性驗(yàn)證都不是安全有效的,這時(shí)候就要求我們在開發(fā)的時(shí)候在服務(wù)端也對數(shù)據(jù)的有效性進(jìn)行驗(yàn)證。 SpringMVC 自身對數(shù)據(jù)在服務(wù)端的校驗(yàn)(Hibernate Validator)有一個(gè)比較好的支持,它能將我們提交到服務(wù)端的數(shù)據(jù)按照我們事先的約定進(jìn)行數(shù)據(jù)有效性驗(yàn)證,對于不合格的數(shù)據(jù)信息 SpringMVC 會把它保存在錯(cuò)誤對象中(Errors接口的子類),這些錯(cuò)誤信息我們也可以通過 SpringMVC 提供的標(biāo)簽(form:errors)在前端JSP頁面上進(jìn)行展示。或者使用攔截器 after 方法對處理錯(cuò)誤信息進(jìn)行處理后傳遞給頁面(我們使用JSON請求的時(shí)候就需要這樣做)。
- 引入包
//https://mvnrepository.com/artifact/org.hibernate/hibernate-validator
compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.4.1.Final'
//https://mvnrepository.com/artifact/javax.el/javax.el-api
compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'
2.配置驗(yàn)證實(shí)體
public class Items {
private Integer id;
private String name;
@NotNull(message = "{product.priceisnull}")
@Min(value = 0,message = "{product.pricenotillegue}")
private Float price;
private String pic;
@Future(message="{product.creattimeerror}")
// @NotEmpty(message = "{product.dateisnull}")
private Date createtime;
@NotNull(message = "{product.detailisnull}")
private String detail;
}
- 配置驗(yàn)證器和國際化
<mvc:annotation-driven conversion-service="conversionService" validator="validator1"/>
<!-- 驗(yàn)證配置,告知srpingmvc,我使用的是Hibernate驗(yàn)證框架來完成的驗(yàn)證 -->
<bean id="validator1" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!--不設(shè)置則默認(rèn)為classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource"/>
</bean>
<!-- 國際化的消息資源文件(本系統(tǒng)中主要用于顯示/錯(cuò)誤消息定制) -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" >
<list>
<!-- 在web環(huán)境中一定要定位到classpath 否則默認(rèn)到當(dāng)前web應(yīng)用下找 -->
<value>classpath:message/errormessage</value>
<!--<value>/WEB-INF/resource/message/errormessage</value>-->
</list>
</property>
<property name="useCodeAsDefaultMessage" value="false"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="cacheSeconds" value="60"/>
</bean>
- src\main\resources\message\errormessage_zh_CN.properties
product.dateisnull=創(chuàng)建時(shí)間不能為空!
product.detailisnull = 描述不能為空!
product.priceisnull=商品價(jià)格不能為空!
product.pricenotillegue=商品價(jià)格不合法!
product.creattimeerror=日期必須為將來時(shí)刻!
- 輸入幾個(gè)空值輸出驗(yàn)證結(jié)果
日期必須為將來時(shí)刻!
商品價(jià)格不能為空!
部分頁面:editItem.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>
<script type="text/javascript" src="<%=basePath%>js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// alert(1);
var params = '{"id": 1,"name": "測試商品","price": 99.9,"detail": "測試商品描述","pic": "123456.jpg","more":{"one":"one"}}';
// $.post(url,params,function(data){
//回調(diào)
// },"json");//
$.ajax({
url : "${pageContext.request.contextPath }/json.action",
data : params,
contentType : "application/json;charset=UTF-8",//發(fā)送數(shù)據(jù)的格式
type : "post",
dataType : "json",//回調(diào)
success : function(data){
// alert(data.more.one);
alert(data[0].username);
},
});
});
</script>
</head>
<body>
<!-- 上傳圖片是需要指定屬性 enctype="multipart/form-data" -->
<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" >
<%--<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">--%>
<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名稱</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品價(jià)格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品日期</td>
<td><input type="text" name="createtime" value="${item.createtime }" /></td>
</tr>
<tr>
<td>商品圖片</td>
<td>
<c:if test="${item.pic != null}">

<br/>
</c:if>
<input type="file" name="pic"/>
</td>
</tr>
<tr>
<td>商品簡介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
error.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML >
<html>
<head>
<title>Java驗(yàn)證框架測試</title>
</head>
<body>
${items.toString()}
${errors.toString()}
<form:form method="post" modelAttribute="items" action="${pageContext.request.contextPath }/validator/updateitem.action">
<h1><form:errors path="price" /></h1><!-- path的值可以為 * ,表示顯示所有錯(cuò)誤 -->
<h1><form:errors path="*" /></h1>
<%--<form:input path="username" /><br/>--%>
<%--<form:input path="password" /><br/>--%>
<input type="submit" value="提交"/>
</form:form>
</body>
</html>
<%--<%@ tag pageEncoding="UTF-8" description="顯示字段錯(cuò)誤消息" %>--%>
<%--<%@ attribute name="commandName" type="java.lang.String" required="true" description="命令對象名稱" %>--%>
<%--<%@ attribute name="errorPosition" type="java.lang.String" required="false" description="錯(cuò)誤消息位置,可以是 topLeft, topRight, bottomLeft, centerRight, bottomRight" %>--%>
<%--<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>--%>
<%--<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>--%>
<%--<c:if test="${empty errorPosition}">--%>
<%--<c:set var="errorPosition" value="topRight"/>--%>
<%--</c:if>--%>
<%--<spring:hasBindErrors name="${commandName}">--%>
<%--<c:if test="${errors.fieldErrorCount > 0}">--%>
<%--<c:forEach items="${errors.fieldErrors}" var="error">--%>
<%--<spring:message var="message" code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>--%>
<%--<c:if test="${not empty message}">--%>
<%--$("[name='${error.field}']")--%>
<%--.validationEngine("showPrompt", "${message}", "error", "${errorPosition}", true)--%>
<%--.validationEngine("updatePromptsPosition");--%>
<%--</c:if>--%>
<%--</c:forEach>--%>
<%--</c:if>--%>
<%--</spring:hasBindErrors>--%>