這篇文章主要介紹“springboot參數(shù)格式怎么校驗(yàn)”,在日常操作中,相信很多人在springboot參數(shù)格式怎么校驗(yàn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”springboot參數(shù)格式怎么校驗(yàn)”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
創(chuàng)新互聯(lián)專注于易門企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站開發(fā)。易門網(wǎng)站建設(shè)公司,為易門等地區(qū)提供建站服務(wù)。全流程按需制作網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
@Validated
字面意思校驗(yàn)
@RequestBody
該注解不用多說,意思是接收為json格式的參數(shù)
@Validated
字面意思校驗(yàn), 需要配合@NotBlank 或者 @NotNull 注解才能生效
進(jìn)入到請求體參數(shù)中。
org.springframework.boot spring-boot-starter-validation
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 = "測試", 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> 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; } }
到此,關(guān)于“springboot參數(shù)格式怎么校驗(yàn)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!