SpringMVC數(shù)據(jù)綁定流程之?dāng)?shù)據(jù)校驗(yàn)

上篇講到數(shù)據(jù)綁定的數(shù)據(jù)轉(zhuǎn)化,接下來我們開一下數(shù)據(jù)校驗(yàn),這邊主要講一下JSR-303整合到SpringMVC中。

pom.xml

 <properties>
        <hibernate-validator.version>5.2.4.Final</hibernate-validator.version>
        <validation-api.version>1.1.0.Final</validation-api.version>
    </properties>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>${validation-api.version}</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>${hibernate-validator.version}</version>
</dependency>

dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 校驗(yàn)器注入到處理器適配器中 -->
    <mvc:annotation-driven validator="validator"/>
    <context:component-scan base-package="validator"/>

    <!-- 國(guó)際化的消息資源文件(本系統(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:messages</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage" value="false"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="cacheSeconds" value="60"/>
    </bean>

    <!-- 以下 validator  ConversionService 在使用 mvc:annotation-driven 會(huì)自動(dòng)注冊(cè)-->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- hibernate校驗(yàn)器-->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        <!-- 如果不加默認(rèn)到 使用classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource"/>
    </bean>

    <!-- ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

messages.properties

user.id.null=用戶編號(hào)不能為空
user.name.null=用戶名不能為空
user.name.length.illegal=用戶名長(zhǎng)度必須在5到20之間
user.name.illegal=用戶名必須是字母
user.password.null=密碼不能為空

核心類

@Data
public class User implements Serializable {
    //使用自定義錯(cuò)誤信息
    @NotNull(message = "{user.id.null}")
    private Long id;
    @NotEmpty(message = "{user.name.null}")
    @Length(min = 5, max = 20, message = "{user.name.length.illegal}")
    @Pattern(regexp = "[a-zA-Z]{5,20}", message = "{user.name.illegal}")
    private String name;
    @NotNull(message = "{user.password.null}")
    private String password;
}
@Controller
public class UserController {
    @RequestMapping("/save")
    //BindingResult講保存錯(cuò)誤信息,到時(shí)候自己根據(jù)業(yè)務(wù)處理
    public String save(@Valid User user, BindingResult result) {
        if (result.hasErrors()) {
            return "error";
        }
        return "success";
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評(píng)論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • SpringMVC介紹之Validation 對(duì)于任何一個(gè)應(yīng)用而言在客戶端做的數(shù)據(jù)有效性驗(yàn)證都不是安全有效的,這時(shí)...
    yongguang423閱讀 1,230評(píng)論 0 16
  • Spring MVC一、什么是 Spring MVCSpring MVC 屬于 SpringFrameWork 的...
    任任任任師艷閱讀 3,535評(píng)論 0 32
  • 圖 | 文 麥咚 山鬼 演唱:winky詩 作詞:屈原 作曲:winky詩 編曲:winky詩 后期:winky詩...
    麥咚閱讀 571評(píng)論 1 6

友情鏈接更多精彩內(nèi)容