SpringMvc服务器端数据校验

SpringMvc服务器端数据校验

1.为什么需要服务端校验?
最早的校验,就是服务端校验。早期的网站,用户输入一个邮箱地址,校验邮箱地址需要将地址发送到服务端,服务端进行校验,校验成功后,给前端一个响应。有了JavaScript,校验工作可以放在前端去执行。那么为什么还需要服务端校验呢? 因为前端传来的数据不可信。前端很容易获取都后端的数据接口,如果有人绕过页面,就会出现非法数据,所以服务端也要数据校验,总的来说:

1.前端校验要做,目的是为了提高用户体验

 2.后端校验也要做,目的是为了数据安全
2.普通校验

Springmvc本身没有校验功能,它使用hibernate的校验框架,hibernate的校验框架和orm没有关系

2.1.引入相关jar包

在这里插入图片描述

2.2创建properties文件

属性文件用来声明错误提示信息

在这里插入图片描述

2.3在springmvc的配置文件中配置如下
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
	<context:component-scan base-package="cn.springmvc.controller"></context:component-scan>
	
	<!--添加对JSR-303验证框架的支持  -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="validatemessageSource"/>
    </bean>
   
    <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
        <property name="basename" value="classpath:ValidateMessages"/>  
        <property name="fileEncodings" value="utf-8"/>  
        <property name="cacheSeconds" value="120"/>  
    </bean>	
</beans>
2.4Bean对象中配置校验规则

在这里插入图片描述

在这里插入图片描述

2.5Controller中校验

在这里插入图片描述

2.6jsp页面中获取错误信息

在这里插入图片描述

3.分组校验

为什么需要分组校验?
因为一个对象有多个属性,而不同的controller校验的需求是不一样的,必须c1只需要校验对象的账号是否为空就可以了,而c2不光要校验账号为空还需要校验手机号必须不能为空,这时分组校验就能解决这个问题了。实现步骤如下:

3.1定义分组

在这里插入图片描述

3.2使用分组

在这里插入图片描述

3.3controller中使用

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值