您好,登錄后才能下訂單哦!
這篇文章主要介紹“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。