`
阅读更多

spring mVC提供了很方便的校验,如下:

 

(1)依赖包:

validation-api.jar
hibernate-validator.jar

通过maven引入

	<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.2.Final</version>
		</dependency>

 

(2)要验证的实体类

import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class Person {
	 
	 @NotNull(message = "用户名称不能为空") 
	 private String name;
	 
	 @Max(value = 100, message = "年龄不能大于100岁") 
	 @Min(value= 18 ,message= "必须年满18岁!" )  
	 private int age;
	 
	 //必须是ture	 
	 @AssertTrue(message = "bln4 must is true")
	 private boolean bln;
	 
        //必须是false
	 @AssertFalse(message = "blnf must is falase")
	 private boolean blnf;
	 
	 @DecimalMax(value="100",message="decim最大值是100")
	 private int decimax;
	 
	 @DecimalMin(value="100",message="decim最小值是100")
	 private int decimin;
	 
	// @Length(min=1,max=5,message="slen长度必须在1~5个字符之间")
	 private String slen;
	
	 @NotNull(message = "身份证不能为空") 
         @Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误")
	 private String iDCard;
	 
	 @NotNull(message="密码不能为空")
	 private String password;
	 @NotNull(message="验证密码不能为空")
	 private String rpassword;
	
        get/set方法
}

 (3)构建controller如下

@Controller
public class SpringValidatorTest {
	@RequestMapping("/validator/springtest")
	public void  springte(@Valid Person person,BindingResult result){
		if(result.hasErrors()){
			List<ObjectError>  list = result.getAllErrors();
			for(ObjectError error: list){
				//System.out.println(error.getObjectName());
				//System.out.println(error.getArguments()[0]);
				System.out.println(error.getDefaultMessage());//验证信息
			}
					
		}
	
	}
}

 

 

(4)使用场景:添加或提交修改时进行字段的校验



 登录:


 

 

注意:BindingResult一定要紧跟在实体类的后面,否则报错:

HTTP Status 400 -


type Status report

message

description The request sent by the client was syntactically incorrect.


Apache Tomcat/7.0.53

 

错误的代码:

@RequestMapping(value = "/add",method=RequestMethod.POST)
	public String addSaveNews(@Valid RoleLevel roleLevel, Model model, BindingResult binding) {
		if(binding.hasErrors()){
			model.addAttribute(roleLevel);
			return jspFolder+"/add";
		}
		saveCommon(roleLevel, model);
		return redirectViewAll;
	}

 正确的代码:

@RequestMapping(value = "/add",method=RequestMethod.POST)
	public String addSaveNews(@Valid RoleLevel roleLevel, BindingResult binding, Model model) {
		if(binding.hasErrors()){
			model.addAttribute(roleLevel);
			return jspFolder+"/add";
		}
		saveCommon(roleLevel, model);
		return redirectViewAll;
	}

 

官方资料

Declaring bean constraints

Constraints in Bean Validation are expressed via Java annotations. In this section you will learn how to enhance an object model with these annotations. There are the following three types of bean constraints:

  • field constraints

  • property constraints

  • class constraints

Note

Not all constraints can be placed on all of these levels. In fact, none of the default constraints defined by Bean Validation can be placed at class level. Thejava.lang.annotation.Target annotation in the constraint annotation itself determines on which elements a constraint can be placed. See Chapter 6, Creating custom constraints for more information.

2.1.1. Field-level constraints

Constraints can be expressed by annotating a field of a class. Example 2.1, “Field-level constraints”shows a field level configuration example:

Example 2.1. Field-level constraints

package org.hibernate.validator.referenceguide.chapter02.fieldlevel;

public class Car {

    @NotNull
    private String manufacturer;

    @AssertTrue
    private boolean isRegistered;

    public Car(String manufacturer, boolean isRegistered) {
        this.manufacturer = manufacturer;
        this.isRegistered = isRegistered;
    }

    //getters and setters...
}

When using field-level constraints field access strategy is used to access the value to be validated. This means the validation engine directly accesses the instance variable and does not invoke the property accessor method even if such an accessor exists.

Constraints can be applied to fields of any access type (public, private etc.). Constraints on static fields are not supported, though.

Tip

When validating byte code enhanced objects property level constraints should be used, because the byte code enhancing library won't be able to determine a field access via reflection.

2.1.2. Property-level constraints

If your model class adheres to the JavaBeans standard, it is also possible to annotate the properties of a bean class instead of its fields. Example 2.2, “Property-level constraints” uses the same entity as inExample 2.1, “Field-level constraints”, however, property level constraints are used.

Example 2.2. Property-level constraints

package org.hibernate.validator.referenceguide.chapter02.propertylevel;

public class Car {

    private String manufacturer;

    private boolean isRegistered;

    public Car(String manufacturer, boolean isRegistered) {
        this.manufacturer = manufacturer;
        this.isRegistered = isRegistered;
    }

    @NotNull
    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    @AssertTrue
    public boolean isRegistered() {
        return isRegistered;
    }

    public void setRegistered(boolean isRegistered) {
        this.isRegistered = isRegistered;
    }
}

Note

The property's getter method has to be annotated, not its setter. That way also read-only properties can be constrained which have no setter method.

When using property level constraints property access strategy is used to access the value to be validated, i.e. the validation engine accesses the state via the property accessor method.

Tip

It is recommended to stick either to field or property annotations within one class. It is not recommended to annotate a field and the accompanying getter method as this would cause the field to be validated twice.

2.1.3. Class-level constraints

Last but not least, a constraint can also be placed on the class level. In this case not a single property is subject of the validation but the complete object. Class-level constraints are useful if the validation depends on a correlation between several properties of an object.

The Car class in Example 2.3, “Class-level constraint” has the two attributes seatCount and passengersand it should be ensured that the list of passengers has not more entries than seats are available. For that purpose the @ValidPassengerCount constraint is added on the class level. The validator of that constraint has access to the complete Car object, allowing to compare the numbers of seats and passengers.

Refer to Section 6.2, “Class-level constraints” to learn in detail how to implement this custom constraint.

Example 2.3. Class-level constraint

package org.hibernate.validator.referenceguide.chapter02.classlevel;

@ValidPassengerCount
public class Car {

    private int seatCount;

    private List<Person> passengers;

    //...
}

 

 

参考:http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/

http://www.yunmasoft.com

http://blog.csdn.net/xpsharp/article/details/9366865

 

  • 大小: 74 KB
  • 大小: 7.8 KB
  • 大小: 25.7 KB
1
0
分享到:

相关推荐

    Spring mvc validator 需要的校验jar包

    spring mvc校验框架所需的几个jar包hibernate-validator-6.0.7.Final.jar、logging-3.1.0.CR2.jar、validator-api-2.0.2.jar

    最全最经典spring-mvc教程

    对于验证,Spring MVC提供了BindingResult和Validator接口,用于校验模型数据的正确性。 另外,Spring MVC与Spring框架的其他组件无缝集成,如Spring AOP(面向切面编程)用于实现日志、事务管理等功能,Spring ...

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    Spring MVC 是一个基于Java的轻量级Web应用框架,它是Spring框架的重要组成部分,主要用于构建Web应用程序的后端控制器。这个教程“Spring MVC - A Tutorial”旨在帮助开发者深入理解和掌握Spring MVC的核心概念和...

    Mastering Spring MVC 4(2015.09)源码

    Spring MVC 是一个强大的Java Web开发框架,它是Spring框架的一部分,专为构建高度可扩展和模块化的Web应用程序而设计。在2015年的版本中,Spring MVC 4已经相当成熟,提供了许多特性来简化开发流程并提高开发效率。...

    Spring MVC 基础实例源码01

    11. **Validation**:Spring提供了数据验证机制,可以通过`@Valid`注解和Validator接口实现对表单数据的校验。 12. **Interceptor**:拦截器,允许在请求处理前后执行自定义逻辑,如日志记录、权限检查等。 13. **...

    spring_validator验证

    Spring Validator验证是Spring MVC框架中的一个关键特性,用于在服务器端对用户输入数据进行校验。在Spring MVC 3.0版本中,引入了注解驱动的验证方式,极大地简化了验证逻辑,使得开发者能够更加方便地处理表单数据...

    spring MVC_快速入门

    Spring MVC 是一个强大的Java Web开发框架,用于构建高效、可维护和模块化的Web应用程序。它作为Spring框架的一部分,提供了一种MVC(Model-View-Controller)架构模式的实现,帮助开发者处理HTTP请求、数据绑定、...

    Spring MVC简单例子

    Spring MVC可以通过自定义Validator或使用JSR-303/JSR-349 Bean Validation进行验证。同时,安全方面需要考虑防止SQL注入和XSS攻击。 7. **视图解析器**:设置ViewResolver,如InternalResourceViewResolver,用来...

    Spring MVC框架的各种依赖包下载

    Spring MVC是Spring框架的一个核心模块,专为构建Web应用程序而设计。它提供了模型-视图-控制器(MVC)架构模式的实现,帮助开发者轻松地处理HTTP请求、数据绑定、视图渲染等任务。在使用Spring MVC时,依赖包的正确...

    resin 支持spring mvc 5.0以上版本 支持Hibernate validation

    Resin 是一款高性能的Java应用服务器,它支持多种Web应用程序框架,包括Spring MVC。Spring MVC是Spring框架的一部分,专门用于构建MVC模式的Web应用程序。本文将深入探讨Resin如何支持Spring MVC 5.0及以上版本,...

    spring mvc入门示例

    7. **验证**:使用Hibernate Validator或Spring的Validator接口,可以在控制器方法执行前验证模型数据。 8. **异常处理**:通过@ControllerAdvice和@ExceptionHandler注解,可以全局地处理异常,提供统一的错误页面...

    Spring MVC、hibernate validator和i18n源代码

    我的博客中的《Spring MVC、hibernate validator和i18n》文章描述的项目的源代码,该文是对Spring mvc, validation和i18n的一个入门级的tutorial。我的博客地址是http://blog.csdn.net/zjysource

    spring mvc框架需要用到的jar包

    Spring MVC 是一个强大的Java Web开发框架,用于构建高效、可维护的Web应用程序。它基于Spring框架,提供了模型-视图-控制器(MVC)架构,简化了开发过程并支持多种集成技术。在搭建Spring MVC环境时,需要引入一...

    Servlet JSP Spring MVC初学指南(alin书签).pdf

    7. **数据绑定与表单验证**:Spring MVC如何自动将表单数据绑定到模型对象,以及使用Hibernate Validator进行验证。 8. **异常处理**:配置全局异常处理器,处理应用程序可能出现的各种错误和异常。 9. **RESTful...

    spring mvc案例+配置+原理详解+架包

    Spring MVC 是一个强大的Java Web开发框架,用于构建可维护、高性能和灵活的Web应用程序。它作为Spring框架的一部分,提供了一种模型-视图-控制器(MVC)架构,简化了处理HTTP请求和响应的复杂性。这个压缩包包含了...

    【面试资料】-(机构内训资料)看透Spring MVC源代码分析与实践.zip

    Spring MVC是Spring框架的核心部分,专门用于构建Web应用程序。它是一个模型-视图-控制器(MVC)架构的实现,提供了灵活的Web开发解决方案。在面试中,对Spring MVC的深入理解和源代码分析能力通常被视为高级Java...

    Spring MVC 教程,快速入门,深入.rar_SpringMVC教程_spring mvc教程_springmvc

    Spring MVC 是一个基于Java的模型-视图-控制器(MVC)架构,是Spring框架的一部分,用于构建Web应用程序。这个“Spring MVC 教程,快速入门,深入.rar”压缩包包含了一个深入的Spring MVC教程,名为“Spring MVC 教程,...

    spring mvc项目后端源码

    10. **验证**:Spring MVC 结合 `Hibernate Validator` 提供了表单验证功能,可以使用 `@Valid` 和 `BindingResult` 进行校验。 11. **RESTful 风格**:通过 `@RestController` 注解和 HTTP 方法注解(`@GetMapping...

    spring3mvc导入包

    为了进行验证和数据绑定,你可能需要用到`spring-validation.jar`(Spring的验证框架,通常与Hibernate Validator一起使用)和`commons-digester.jar`(用于XML配置的解析)。 最后,开发过程中可能还会用到`slf4j-...

    SixDay-Spring MVC(基于Spring MVC实现后台登陆系统验证)的源代码

    Spring MVC框架由DispatcherServlet、Controller、Model、View和Validator等组件构成。DispatcherServlet作为入口,负责请求分发;Controller处理业务逻辑;Model存储数据;View负责展示结果;Validator则用于数据...

Global site tag (gtag.js) - Google Analytics