Springboot 集成 Validated 驗(yàn)證參數(shù)

1 引入

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

2 Controller 中使用

    @PostMapping("/testval")
    public Object testVal(@Validated @RequestBody TGiftPO po){
//        var r = extSchoolMService.sync();
        return Result.success(po);
    }

3 PO 中進(jìn)行標(biāo)記

@Data
public class TGiftPO {

    @NotNull(message = "title 不可為空")
    String title;

    String img;

    Integer score;

}

全局異常類(lèi)中進(jìn)行捕捉

import com.adea.tool.result.Result;
import com.adea.tool.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;


@Slf4j
@ControllerAdvice
public class ValidatedExceptionHandler {

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()){
            List<ObjectError> errors = result.getAllErrors();
            if (errors != null){
                errors.forEach(p ->{
                    FieldError fieldError = (FieldError) p;
                    stringBuilder.append(fieldError.getDefaultMessage());
                });
            }
        }

        return Result.error(ResultCode.USER_PARAM_ERROR,stringBuilder.toString());
    }

}

axios 的配置

          if(error.response.data  &&  error.response.data.message){
                ElMessage({
                    message: error.response.data.message,
                    type: 'error',
                    duration: 3 * 1000
                })
            }

相關(guān)注解

image.png

Ref:

https://blog.csdn.net/qq_32352777/article/details/108424932

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容