Spring MVC 参数检验 (Validated & Valid)

一、Validated和Valid区别

在Spring Mvc中可以使用@Validated和@Valid两个注解来校验Controller 方法参数。

其中@Valid是标准JSR-303规范的标记型注解,用来标记验证属性和方法返回值,进行级联和递归校验。

而@Validated是Spring提供的注解,是标准JSR-303的一个变种(补充),提供了一个分组功能,可以在入参验证时,根据不同的分组采用不同的验证机制。

且两者作用的范围也有些许不一样;
Valid可以用在:方法,字段、枚举的常量,构造函数,方法参数;
Validated可以用在:接口、类、枚举、注解,方法,方法参数。

二、Controller参数校验

在springboot中,基本上使用@Valid和@Validated都可以进行校验,但是在springboot项目,还是推建使用@Validated注解。
在请求接口的场景中,也分为使用@RequestParam、@PathVariable 指定请求参数,例如

@GetMapping("/test")
public String get(@RequestParam(value = "gsbId", required = false) String gsbId){
    
    
	// ... do some thing
}

也有通过在形参中指定某个类型场景,例如:


@Data
public class Pojo{
    
    
	private String a;
}

// pojo中的a = request.getParameter("a"),相当于@RequestParma("a")
@GetMapping("/get")
public String get(Pojo pojo){
    
    
	// ... do some thing
}

@PostMapping("/post")
public Sting post(@RequestBody Pojo pojo){
    
    
	// ... to some ting
}

这两种场景在使用@Validated时会有些不一样。

1、@RequestParam、@PathVariable 指定请求参数

代码示例:

@Validated
@RestController
public class Controller{
    
    
	@GetMapping("/test")
	public String get(@Min(value=10, message="num must greater than 10") @RequestParam("num") Integer num){
    
    
		// ... do some thing
	}
}

注意:

  • @Validated注解标注在类上,标注在方法或者参数上则无效
  • 方法参数中不能有bingResult、errors,bingdingResult、errors

2、在形参中指定POJO类

代码示例:

@RestController
public class Controller{
    
    
	@GetMapping("/get")
	public String get(@Validated Pojo pojo){
    
    
		// ... do some thing
	}
	
	@GetMapping("/post")
	public String post(@Validated @RequestBody Pojo pojo){
    
    
		// ... do some thing
	}
}


public class Pojo{
    
    
	@Min(value=10, message="num must greater than 10")
	private Integer num;
}

注意:

  • 在这种使用场景下,@Validated注解只有标注在方法参数上才会生效
  • 方法参数中不能有bingResult、errors,bingdingResult、errors

最后关于JAVA字段校验(validation)更多的资料可以点击链接查看

猜你喜欢

转载自blog.csdn.net/Mr_rain/article/details/124493271
今日推荐