springboot 參數格式校驗操作

springboot 參數格式校驗

@Validated

字面意思校驗

在這裡插入圖片描述

@RequestBody

該註解不用多說,意思是接收為json格式的參數

@Validated

字面意思校驗, 需要配合@NotBlank 或者 @NotNull 註解才能生效

進入到請求體參數中。

在這裡插入圖片描述

springboot 參數註解校驗

1.添加依賴

<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;
}

2.controller層

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 "參數驗證通過";
    }
}

3.自定義一個拋出異常類

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();
    }
}

4.加一個當檢測第一個參數不合法時立即返回錯誤不會繼續進行校驗

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;
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: