您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍“springboot参数格式怎么校验”,在日常操作中,相信很多人在springboot参数格式怎么校验问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”springboot参数格式怎么校验”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
@Validated
字面意思校验
@RequestBody
该注解不用多说,意思是接收为json格式的参数
@Validated
字面意思校验, 需要配合@NotBlank 或者 @NotNull 注解才能生效
进入到请求体参数中。
<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; }
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 "参数验证通过"; } }
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(); } }
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; } }
到此,关于“springboot参数格式怎么校验”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。