SpringMVC(九)数据校验

服务端校验:springmvc使用validation校验,struts2使用validation校验。都有自己的一套校验规则。
(1)springmvc的validation校验
Springmvc本身没有校验功能,它使用hibernate的校验框架,hibernate的校验框架和orm没有关系。
1、添加jar包
在这里插入图片描述
2、在springmvc.xml中配置validator校验器,基本上直接复制拿过去用即可。
在这里插入图片描述

<!-- 校验器,配置validator -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        <property name="validationMessageSource" ref="validationMessageSource"></property>
    </bean>
    
    <!-- 配置validationMessageSource -->
    <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- 指定校验信息的资源文件的基本文件名称,不包括后缀,后缀默认是properties -->
        <property name="basenames">
            <list>
                <value>classpath:validationMessageSource</value>
            </list>
        </property>
        <!-- 指定文件的编码 -->
        <property name="fileEncodings" value="utf8"></property>
        <!-- 对资源文件内容缓存的时间,单位秒 -->
        <property name="cacheSeconds" value="120"></property>
    </bean>

springmvc.xml配置校验器

3、validationMessageSource.properties
该配置文件的作用就是存储校验失败时的提示文字信息的,也就是相当于将其提取出来放到配置文件中,
在这里插入图片描述
4、在pojo中指定校验规则
在这里插入图片描述
1、items.name.size和items.createtime.notnull:就是读取validationMessageSource.properties中的配置信息。从这里就可以理解该配置文件的意义,防止硬编码。

2、使用注解对需要进行校验的属性进行绑定,而能够使这些注解生效的前提就是配置此前的几个步骤,2.1、2.2、2.3都必不可少
在这里插入图片描述
在这里插入图片描述
5、controller中对其校验绑定进行使用
在这里插入图片描述
6、jsp
在这里插入图片描述
(2)分组式校验
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值