设为首页 加入收藏

TOP

关于SpringMVC之认识Validation(四)
2017-07-05 10:23:30 】 浏览:471
Tags:关于 SpringMVC 认识 Validation
数据验证的规范,这里我不会讲这个规范是怎么回事,只会讲一下JSR-303在SpringMVC中的应用。JSR-303只是一个规范,而Spring也没有对这一规范进行实现,那么当我们在SpringMVC中需要使用到JSR-303的时候就需要我们提供一个对JSR-303规范的实现,Hibernate Validator是实现了这一规范的,这里我将以它作为JSR-303的实现来讲解SpringMVC对JSR-303的支持。


      JSR-303的校验是基于注解的,它内部已经定义好了一系列的限制注解,我们只需要把这些注解标记在需要验证的实体类的属性上或是其对应的get方法上。来看以下一个需要验证的实体类User的代码:


Java代码 
 
import javax.validation.constraints.Min; 
import javax.validation.constraints.NotNull; 
import org.hibernate.validator.constraints.NotBlank; 
 
public class User { 
 
    private String username; 
   
    private String password; 
   
    private int age; 
 
    @NotBlank(message="用户名不能为空") 
    public String getUsername() { 
      return username; 
    } 
 
    public void setUsername(String username) { 
      this.username = username; 
    } 
 
    @NotNull(message="密码不能为null") 
    public String getPassword() { 
      return password; 
    } 
 
    public void setPassword(String password) { 
      this.password = password; 
    } 
 
    @Min(value=10, message="年龄的最小值为10") 
    public int getAge() { 
      return age; 
    } 
 
    public void setAge(int age) { 
      this.age = age; 
    } 
   

 


      我们可以看到我们在username、password和age对应的get方法上都加上了一个注解,这些注解就是JSR-303里面定义的限制,其中@NotBlank是Hibernate Validator的扩展。不难发现,使用JSR-303来进行校验比使用Spring提供的Validator接口要简单的多。我们知道注解只是起到一个标记性的作用,它是不会直接影响到代码的运行的,它需要被某些类识别到才能起到限制作用。使用SpringMVC的时候我们只需要把JSR-303的实现者对应的jar包放到classpath中,然后在SpringMVC的配置文件中引入MVC Namespace,并加上<mvn:annotation-driven/>就可以非常方便的使用JSR-303来进行实体对象的验证。加上了<mvn:annotation-driven/>之后Spring会自动检测classpath下的JSR-303提供者并自动启用对JSR-303的支持,把对应的校验错误信息放到Spring的Errors对象中。这时候SpringMVC的配置文件如下所示:


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:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
     
    <mvc:annotation-driven/> 
</beans> 
 


      接着

首页 上一页 1 2 3 4 5 6 下一页 尾页 4/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Linux编程之select 详解 下一篇Hibernate Session中的save(),upd..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目