輸入表單驗證

栓栓和霜霜發表於2024-05-14

1.新增依賴

           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-validation</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

2.建立實體類,以下面舉例

@Data
public class AddressBookDto {


    //使用者id
    @NotNull
    @Min(2222)
    private Long userId;


    //收貨人 或 僱員名稱
    @NotNull
    @Size(min = 2, max = 30)
    private String consignee;


    //手機號
    private String phone;


    //性別 0 女 1 男
    private String sex;


    //省級區劃編號
    private String provinceCode;


    //省級名稱
    private String provinceName;


    //市級區劃編號
    private String cityCode;


    //市級名稱
    private String cityName;


    //區級區劃編號
    private String districtCode;


    //區級名稱
    private String districtName;


    //詳細地址
    private String detail;


    //標籤 比如 公司、家
    private String label;

    //是否預設 0 否 1是
    private Integer isDefault;


    //是否刪除

    private Integer isDeleted;
}

3.在controller程式碼裡面加入BindingResult bindingResult,在要驗證的實體中前加@Valid

    @PostMapping("/save")
    public Result<AddressBook> save(@Parameter(description = "addressBookDto")
                                        @RequestBody @Valid AddressBookDto addressBookDto, BindingResult bindingResult) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressBookDto, addressBook);
        return Result.success(addressBookService.save(addressBook));
    }

4.在AOP中加入以下程式碼

@Aspect
@Component
public class WebLogAspect {

    @Autowired
    ObjectMapper objectMapper;
    Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Around("execution(* com.integration.scaffold.relationaldataaccess.mysql.controller.*.*(..))")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
        // 記錄呼叫的方法和引數
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Long startTime = System.currentTimeMillis();
        logger.info("請求ip是:{}", request.getRemoteAddr());
        logger.info("請求url是: {}", request.getRequestURL().toString());
        logger.info("請求方法是: {}", request.getMethod());
        logger.info("處理Method:{},請求方法:{}", pjp.getSignature().getDeclaringTypeName(), pjp.getSignature().getName());
        logger.info("請求引數是:{}", pjp.getArgs());
        for (Object obj : pjp.getArgs()) {
            if (obj instanceof BindingResult) {
                BindingResult bindingResult = (BindingResult) obj;
                if (bindingResult.hasErrors()) {
                    List<ObjectError> errors = bindingResult.getAllErrors();
                    StringBuffer sb = new StringBuffer();
                    for (ObjectError objectError : errors) {
                        sb.append(Arrays.stream(objectError.getArguments()).findFirst() + "---" +
                                objectError.getCode() + "---" + objectError.getDefaultMessage());
                    }
                    logger.info("返回結果是:{}", Result.fail(sb.toString()));
                    Long endTime = System.currentTimeMillis();
                    logger.info("執行方法耗時:{}秒", (endTime - startTime) / 1000.0);
                    return Result.fail(sb.toString());

                }
            }
        }
        Object retVal = pjp.proceed();
        // stop stopwatch
        logger.info("返回結果是:{}", objectMapper.writeValueAsString(retVal));
        Long endTime = System.currentTimeMillis();
        logger.info("執行方法耗時:{}秒", (endTime - startTime) / 1000.0);
        return retVal;
    }
}

啟動專案,進行測試

當不符合條件時:

當符合條件時:

點選比如@Min所在的包裡面有很多的驗證條件,都是可以使用的哦

相關文章