你还在使用一堆if...else if...else来校验数据吗?看完这篇文章,你可以不需要再写一堆if...else...了,只需要使用一个注解,就能对前端传来的数据进行有效性判断。
springboot项目中使用validation的步骤:
1、pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、实体类内使用注解
比如,下面是一个登录用的dto对象,需要保证用户名密码都不能为空
package cn.edu.sgu.www.authority.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
/**
* @author heyunlin
* @version 1.0
*/
@Data
public class UserLoginDTO {
/**
* 用户名
*/
@NotNull(message = "用户名不允许为空")
@NotEmpty(message = "用户名不允许为空")
private String username;
/**
* 密码
*/
@NotNull(message = "密码不允许为空")
@NotEmpty(message = "密码不允许为空")
private String password;
}
3、使用@Valid或@Validated注解
controller的方法参数上使用@Valid或者@Validated注解开启校验
package cn.edu.sgu.www.authority.controller;
import cn.edu.sgu.www.authority.annotation.AnonymityAccess;
import cn.edu.sgu.www.authority.dto.UserLoginDTO;
import cn.edu.sgu.www.authority.restful.JsonResult;
import cn.edu.sgu.www.authority.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author heyunlin
* @version 1.0
*/
@RestController
@Api(tags = "用户控制器类")
@RequestMapping(path = "/user", produces="application/json;charset=utf-8")
public class UserController {
private final UserService service;
@Autowired
public UserController(UserService service) {
this.service = service;
}
@AnonymityAccess
@ApiOperation("登录认证")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public JsonResult<Void> login(@Validated UserLoginDTO loginDTO) {
service.login(loginDTO);
return JsonResult.success();
}
}
当数据格式校验不通过时,会抛出异常org.springframework.validation.BindException
除此之外,Validation框架还有很多注解,用于进行不同格式的验证:
注解 | 作用 |
@NotEmpty | 只能添加在String类型上,不许为空字符串,即"" |
@NotBlank | 只能添加在String类型上,不允许为空白,例如普通的空格可视为空白,使用TAB键输入的内容也是空白 |
@Size | 限制数值的大小 |
@Min | 限制数值的最小值 |
@Max | 限制数值的最大值 |
@Range | 可以配置min和max属性,同时限制最小值和最大值 |
@Pattern | 只能添加在String类型上,通过指定的正则表达式进行验证 |
好了,文章就分享到这里了,看完不要忘了点赞+收藏哦~