Springmvc 數(shù)據(jù)校驗和國際化<12>

1.spring4.0整合了validation驗證功能
2.SpringMVC 使用驗證框架 Bean Validation(上)

??對于任何一個應(yīng)用而言在客戶端做的數(shù)據(jù)有效性驗證都不是安全有效的,這時候就要求我們在開發(fā)的時候在服務(wù)端也對數(shù)據(jù)的有效性進(jìn)行驗證。 SpringMVC 自身對數(shù)據(jù)在服務(wù)端的校驗(Hibernate Validator)有一個比較好的支持,它能將我們提交到服務(wù)端的數(shù)據(jù)按照我們事先的約定進(jìn)行數(shù)據(jù)有效性驗證,對于不合格的數(shù)據(jù)信息 SpringMVC 會把它保存在錯誤對象中(Errors接口的子類),這些錯誤信息我們也可以通過 SpringMVC 提供的標(biāo)簽(form:errors)在前端JSP頁面上進(jìn)行展示?;蛘呤褂脭r截器 after 方法對處理錯誤信息進(jìn)行處理后傳遞給頁面(我們使用JSON請求的時候就需要這樣做)。

  1. 引入包

//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.配置驗證實體

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;
}
  1. 配置驗證器和國際化
 <mvc:annotation-driven conversion-service="conversionService" validator="validator1"/>

  <!-- 驗證配置,告知srpingmvc,我使用的是Hibernate驗證框架來完成的驗證 -->
    <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)中主要用于顯示/錯誤消息定制) -->
    <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>
  1. src\main\resources\message\errormessage_zh_CN.properties
product.dateisnull=創(chuàng)建時間不能為空!
product.detailisnull = 描述不能為空!
product.priceisnull=商品價格不能為空!
product.pricenotillegue=商品價格不合法!
product.creattimeerror=日期必須為將來時刻!
  1. 輸入幾個空值輸出驗證結(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>商品價格</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}">
                        ![](/pic/${item.pic})
                        <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驗證框架測試</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的值可以為 * ,表示顯示所有錯誤 -->
  <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="顯示字段錯誤消息" %>--%>
<%--<%@ attribute name="commandName" type="java.lang.String" required="true" description="命令對象名稱" %>--%>
<%--<%@ attribute name="errorPosition" type="java.lang.String" required="false" description="錯誤消息位置,可以是 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>--%>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容