您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。