springboot 参数格式校验操作
作者:taiguolaotu 时间:2023-10-16 08:53:32
springboot 参数格式校验
@Validated
字面意思校验
@RequestBody
该注解不用多说,意思是接收为json格式的参数
@Validated
字面意思校验, 需要配合@NotBlank 或者 @NotNull 注解才能生效
进入到请求体参数中。
springboot 参数注解校验
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
package com.xl.annotation;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class User {
@NotNull(message = "ID不能为空")
@Range(min = 1, max = 100, message = "ID必须在1到100之间")
private Integer id;
@NotNull(message = "姓名不能为空")
@Length(min = 2, max = 6, message = "姓名必须在2到6位之间")
private String name;
@NotNull(message = "余额不能为空")
@DecimalMax(value = "30.50", message = "余额不能超过30.5")
@DecimalMin(value = "1.50", message = "余额不能低于1.5")
private BigDecimal amount;
@NotNull(message = "生日不能为空")
@Past(message = "生日必须是过去")
private Date birthday;
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$", message = "手机号格式错误")
private String phone;
}
2.controller层
package com.xl.annotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.ValidationException;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
@RestController
@Validated
@Api(value = "手机验证",description = "手机验证")
public class MobileController {
@ApiOperation("手机验证")
@RequestMapping("/phone")
public String mobilePattern( Phone phone){
return "chengg";
}
@PostMapping("/getUser")
@ApiOperation("手机验证12")
public String getUserStr( @NotNull(message = "name 不能为空")@RequestParam String name,
@Max(value = 99, message = "不能大于99岁")@RequestParam Integer age) {
return "name: " + name + " ,age:" + age;
}
/* @PostMapping("/getUser1")
@ApiOperation("手机验证c")
public String getUser(@RequestBody @Validated User user, BindingResult bindingResult) {
validData(bindingResult);
return "name: " + user.getName() + " ,age:" + user.getAge();
}*/
private void validData(BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
StringBuffer sb = new StringBuffer();
for (ObjectError error : bindingResult.getAllErrors()) {
sb.append(error.getDefaultMessage());
}
throw new ValidationException(sb.toString());
}
}
@PostMapping("/test")
@ApiOperation(value = "测试", notes = "")
public String test(@ApiParam(name = "test", value = "参数", required = true) @Validated @RequestBody User test, BindingResult bindingResult) {
validData(bindingResult);
if(bindingResult.hasErrors()){
String errorMsg = bindingResult.getFieldError().getDefaultMessage();
return errorMsg;
}
return "参数验证通过";
}
}
3.自定义一个抛出异常类
package com.xl.annotation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;
/**
* 自定义验证抛出异常
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ValidationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handle(ValidationException exception) {
if(exception instanceof ConstraintViolationException){
ConstraintViolationException exs = (ConstraintViolationException) exception;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
//打印验证不通过的信息
System.out.println(item.getMessage());
}
}
return exception.getMessage();
}
}
4.加一个当检测第一个参数不合法时立即返回错误不会继续进行校验
package com.xl.annotation;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
@Configuration
public class ValidatorConf {
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
.configure()
.failFast( true )
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
}
来源:https://blog.csdn.net/taiguolaotu/article/details/118336396
标签:springboot,参数,校验
0
投稿
猜你喜欢
Kotlin 协程与挂起函数及suspend关键字深入理解
2023-09-19 01:04:25
Android如何禁止向EditText控件中输入内容详解
2021-07-29 05:01:11
C#数据表格(DataGridView)控件的应用案例
2023-04-11 11:10:24
SpringBoot2.3新特性优雅停机详解
2023-11-28 07:59:43
springboot实现注册加密与登录解密功能(demo)
2021-12-15 15:10:08
Idea导入eureka源码实现过程解析
2023-06-11 11:52:24
C# 修改文件的创建、修改和访问时间的示例
2023-06-09 23:18:50
Java常用类String的面试题汇总(java面试题)
2023-11-23 20:40:45
Android通过HTTP协议实现断点续传下载实例
2022-12-05 23:39:05
协定需要会话,但是绑定“BasicHttpBinding”不支持它或者因配置不正确而无法支持它
2023-03-17 16:44:34
JAVA中的final关键字用法实例详解
2021-06-25 12:10:08
C#装箱和拆箱的原理介绍
2022-06-18 02:33:17
C#实现获取Excel中图片所在坐标位置
2021-10-14 23:36:18
详解Java中的字节码增强技术
2022-08-20 06:25:12
基于Spring概念模型:PathMatcher 路径匹配器
2022-08-20 12:52:38
Java数据结构之链表详解
2023-10-20 09:14:08
Android横竖屏幕切换小结
2023-04-15 08:03:20
Android Application级别自定义Toast
2022-01-02 03:41:45
Spring MVC整合 freemarker及使用方法
2022-06-06 16:41:41
使用java springboot设计实现的图书管理系统(建议收藏)
2023-11-25 00:54:49