首页 Java java教程 SpringMVC学习系列(6) 之 数据验证

SpringMVC学习系列(6) 之 数据验证

Mar 03, 2017 am 10:58 AM
springmvc

在系列(4)、(5)中我们展示了如何绑定数据,绑定完数据之后如何确保我们得到的数据的正确性?这就是我们本篇要说的内容 —> 数据验证。

这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://www.php.cn/下载需要的jar包,这里以4.3.1.Final作为演示,解压后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中。

配置之前项目中的springservlet-config.xml文件,如下:

<!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />
    
    <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="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
    <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>
登录后复制


其中<property name="basename" value="classpath:validatemessages"/>中的classpath:validatemessages为注解验证消息所在的文件,需要我们在resources文件夹下添加。

在com.demo.web.controllers包中添加一个ValidateController.java内容如下:

package com.demo.web.controllers;import java.security.NoSuchAlgorithmException;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.ValidateModel;

@Controller
@RequestMapping(value = "/validate")public class ValidateController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model){        if(!model.containsAttribute("contentModel")){
            model.addAttribute("contentModel", new ValidateModel());
        }        return "validatetest";
    }
    
    @RequestMapping(value="/test", method = {RequestMethod.POST})    public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{        
        //如果有验证错误 返回到form页面
        if(result.hasErrors())            return test(model);        return "validatesuccess";     
    }
    
}
登录后复制


其中@Valid @ModelAttribute("contentModel") ValidateModel validateModel的@Valid 意思是在把数据绑定到@ModelAttribute("contentModel") 后就进行验证。

在com.demo.web.models包中添加一个ValidateModel.java内容如下:

package com.demo.web.models;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.NotEmpty;import org.hibernate.validator.constraints.Range;public class ValidateModel{
    
    @NotEmpty(message="{name.not.empty}")    private String name;
    @Range(min=0, max=150,message="{age.not.inrange}")    private String age;
    @NotEmpty(message="{email.not.empty}")
    @Email(message="{email.not.correct}")    private String email;    
    public void setName(String name){        this.name=name;
    }    public void setAge(String age){        this.age=age;
    }    public void setEmail(String email){        this.email=email;
    }    
    public String getName(){        return this.name;
    }    public String getAge(){        return this.age;
    }    public String getEmail(){        return this.email;
    }
    
}
登录后复制


在注解验证消息所在的文件即validatemessages.properties文件中添加以下内容:

name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002
age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002
email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002
email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002
登录后复制


其中name.not.empty等分别对应了ValidateModel.java文件中message=”xxx”中的xxx名称,后面的内容是在输入中文是自动转换的ASCII编码,当然你也可以直接把xxx写成提示内容,而不用另建一个validatemessages.properties文件再添加,但这是不正确的做法,因为这样硬编码的话就没有办法进行国际化了。

在views文件夹中添加validatetest.jsp和validatesuccess.jsp两个视图,内容分别如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ taglib prefix="form" uri="http://www.php.cn/" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>
    <form:form modelAttribute="contentModel" method="post">     
        
        <form:errors path="*"></form:errors><br/><br/>
            
        name:<form:input path="name" /><br/>
        <form:errors path="name"></form:errors><br/>
        
        age:<form:input path="age" /><br/>
        <form:errors path="age"></form:errors><br/>
        
        email:<form:input path="email" /><br/>
        <form:errors path="email"></form:errors><br/>

        <input type="submit" value="Submit" />
        
    </form:form>  </body></html>
登录后复制


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><!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>Insert title here</title></head><body>
    验证成功!</body></html>
登录后复制


其中特别要指出的是validatetest.jsp视图中<form:form modelAttribute="contentModel" method="post">modelAttribute="xxx"后面的名称xxx必须与对应的@Valid @ModelAttribute("xxx") 中的xxx名称一致,否则模型数据和错误信息都绑定不到。

<form:errors path="name">form:errors>即会显示模型对应属性的错误信息,当path="*"时则显示模型全部属性的错误信息。

运行测试:

1

直接点击提交:

2

可以看到正确显示了设置的错误信息。

填写错误数据提交:

3

可以看到依然正确显示了设置的错误信息。

填写正确数据提交:

4

5

可以看到验证成功。

 

下面是主要的验证注解及说明:

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,CollectionMap and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

 

更多信息请参考官方文档:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

 

注: 之前没注意前11篇的示例代码,不知道为什么当时打包上传上去的是没有.project项目文件的,导致下载后不能直接导入eclipse运行,虚拟机又 被我删掉了,这些示例代码也没有备份,但是代码文件还在的,所以可以新建一个Dynamic Web Project把对应的配置文件和controller还有view导入就可以了,给大家造成的不便说声抱歉。

以上就是SpringMVC学习系列(6) 之 数据验证的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SpringBoot与SpringMVC的比较及差别分析 SpringBoot与SpringMVC的比较及差别分析 Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

比较SpringBoot与SpringMVC的差异是什么? 比较SpringBoot与SpringMVC的差异是什么? Dec 29, 2023 am 10:46 AM

SpringBoot与SpringMVC的不同之处在哪里?SpringBoot和SpringMVC是两个非常流行的Java开发框架,用于构建Web应用程序。尽管它们经常分别被使用,但它们之间的不同之处也是很明显的。首先,SpringBoot可以被看作是一个Spring框架的扩展或者增强版。它旨在简化Spring应用程序的初始化和配置过程,以帮助开发人

SpringBoot与SpringMVC的区别是什么? SpringBoot与SpringMVC的区别是什么? Dec 29, 2023 pm 05:19 PM

SpringBoot和SpringMVC是Java开发中常用的两个框架,它们都是由Spring框架所提供的,但在功能和使用方式上有着一些区别。本文将分别介绍SpringBoot和SpringMVC的特点和区别。一、SpringBoot的特点:简化配置:SpringBoot通过约定优于配置的原则,大大简化了项目的配置过程。它可以自动配置项目所需要的参数,开发人

springboot和springmvc有哪些区别 springboot和springmvc有哪些区别 Jun 07, 2023 am 10:10 AM

springboot和springmvc区别是:​1、含义不同;2、配置不同;3、依赖项不同;4、开发时间不同;5、生产力不同;6、实现JAR打包功能的方式不同;7、是否提供批处理功能;8、作用不同;9、社区和文档支持不同;10、是否需要部署描述符。

spring和springmvc有哪些区别 spring和springmvc有哪些区别 Dec 29, 2023 pm 05:02 PM

spring和springmvc的区别:1、定位和功能;2、核心功能;3、应用领域;4、扩展性。详细介绍:1、定位和功能,Spring是一个综合性的应用程序开发框架,提供了依赖注入、面向切面编程、事务管理等功能,旨在简化企业级应用程序的开发,而Spring MVC是Spring框架中的一个模块,用于Web应用程序的开发,实现了MVC模式;2、核心功能等等。

Java API 开发中使用 SpringMVC 进行 Web 服务处理 Java API 开发中使用 SpringMVC 进行 Web 服务处理 Jun 17, 2023 pm 11:38 PM

随着互联网的发展,Web服务越来越普遍。JavaAPI作为一种应用编程接口,也在不断地推出新的版本来适应不同的应用场景。而SpringMVC作为一种流行的开源框架,能够帮助我们轻松地构建Web应用程序。本文将详细讲解在JavaAPI开发中,如何使用SpringMVC进行Web服务处理,包括配置SpringMVC、编写控制器、使用

Java的SpringMVC拦截器怎么用 Java的SpringMVC拦截器怎么用 May 13, 2023 pm 02:55 PM

拦截器(interceptor)的作用SpringMVC的拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(InterceptorChain)。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。拦截器也是AOP思想的具体实现。拦截器和过滤器区别区别过滤器(Filter)拦截器(Intercepter)使用范围是servlet规范中的一部分,任何JavaWeb工程都可以使用是Spri

比较SpringBoot和SpringMVC的异同点 比较SpringBoot和SpringMVC的异同点 Dec 29, 2023 am 08:30 AM

解析SpringBoot和SpringMVC之间的异同SpringBoot和SpringMVC是Java领域中非常重要的开发框架。虽然它们都属于Spring框架的一部分,但是在使用和功能上有一些明显的区别。本文将对SpringBoot和SpringMVC进行比较,解析它们之间的异同。首先,让我们来了解一下SpringBoot。SpringBo

See all articles