您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)springboot 中怎么校驗(yàn)參數(shù)格式,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
@Validated
字面意思校驗(yàn)
@RequestBody
該注解不用多說,意思是接收為json格式的參數(shù)
@Validated
字面意思校驗(yàn), 需要配合@NotBlank 或者 @NotNull 注解才能生效
進(jìn)入到請(qǐng)求體參數(shù)中。
<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 = "手機(jī)號(hào)不能為空") @Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$", message = "手機(jī)號(hào)格式錯(cuò)誤") 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 = "手機(jī)驗(yàn)證",description = "手機(jī)驗(yàn)證") public class MobileController { @ApiOperation("手機(jī)驗(yàn)證") @RequestMapping("/phone") public String mobilePattern( Phone phone){ return "chengg"; } @PostMapping("/getUser") @ApiOperation("手機(jī)驗(yàn)證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("手機(jī)驗(yàn)證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 = "測(cè)試", notes = "") public String test(@ApiParam(name = "test", value = "參數(shù)", required = true) @Validated @RequestBody User test, BindingResult bindingResult) { validData(bindingResult); if(bindingResult.hasErrors()){ String errorMsg = bindingResult.getFieldError().getDefaultMessage(); return errorMsg; } return "參數(shù)驗(yàn)證通過"; } }
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; /** * 自定義驗(yàn)證拋出異常 */ @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) { //打印驗(yàn)證不通過的信息 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 中怎么校驗(yàn)參數(shù)格式,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。