日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

springboot-數據驗證及全局異常處理

作者:挽留自己的頭發 更新時間: 2022-07-23 編程語言

一. 引入依賴

<!--引入jsr303(支持驗證框架)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

JSR-303是Java EE 6中的一項子規范,叫做Bean Validation

二. 添加驗證規則

2.1 添加在JavaBean上面

import javax.validation.constraints.*;

public class TestDto {
    @NotEmpty(message = "學號不能為空")
    @Size(min = 6,max = 6,message = "學好必須是六位")
    private String e_id;
    @NotEmpty(message = "名字不能為空")
    private String e_name;
    @NotNull(message ="成績不能為null")
    @Min(value = 0,message = "成績不得為負數")
    @Max(value = 100,message = "成績最大是100")
    private Integer e_score;

    public String getE_id() {
        return e_id;
    }

    public void setE_id(String e_id) {
        this.e_id = e_id;
    }

    public String getE_name() {
        return e_name;
    }

    public void setE_name(String e_name) {
        this.e_name = e_name;
    }

    public Integer getE_score() {
        return e_score;
    }

    public void setE_score(Integer e_score) {
        this.e_score = e_score;
    }
    
}
public class LoginDto {
    //@NotEmpty僅針對String ,集合等
    @NotEmpty(message = "賬號不得為空")
    private String u_id;
    @NotEmpty(message = "密碼不得為空")
    @Size(min = 6,max = 15,message = "密碼必須為6-15")
    private String u_pwd;

    public String getU_id() {
        return u_id;
    }

    public void setU_id(String u_id) {
        this.u_id = u_id;
    }

    public String getU_pwd() {
        return u_pwd;
    }

    public void setU_pwd(String u_pwd) {
        this.u_pwd = u_pwd;
    }
}

添加在Java Bean上面的驗證在使用的時候必須在作為參數的javaBean前面添加@Validated注解,才能生效

@RestController
public class LoginController {
    @PostMapping("/login")
    //對于JavaBean的驗證,在這里加注解@Validated
    public Result doLogin(@Validated @RequestBody LoginDto dto){
        return Result.ok();
    }
}

2.2 添加在控制器參數上

@RestController
@Validated//該注解加在類上表示:本類的方法參數如果有限制(約束)注解,將進行驗證,
// 后端的驗證是必須的,前端的驗證時可以通過技術手段跳過的,后端的驗證才是保障
public class MyController {
    @GetMapping("/say")
    public String sayHello(@NotEmpty(message = "名稱不能為null") String name,
                           @NotNull(message = "年齡必須要填寫")
                           @Min(value=16,message = "最小不能小于16歲")Integer age){
        return "hello"+name;
    }
    @GetMapping("/test")
    public Result testDto(@Validated TestDto testDto){
        return Result.ok("登陸成功");
    }
}

注意:在類上添加了@Validated注解,但是在參數是javaBean的時候還得在參數前添加@Validated注解。

三. 開發全局異常處理

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@RestControllerAdvice//該注解說明本類是一個RestController的攔截器,
// 還可以對controller處理方法添加額外邏輯,做增強處理
public class DemoControllerAdvice {
    //該注解說明本方法是一個異常處理器,即當被攔截的controller處理方法發生指定的異常時,即由本方法處理
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException e){
        log.error("參數不匹配",e);
        Set<ConstraintViolation<?>> set = e.getConstraintViolations();//獲取驗證錯誤集合
        //將驗證錯誤集合中,每一個錯誤的信息取出來,組成一個新的集合,再將新集合中的元素用”,“連接成一個字符串,返回這個字符串
        String msg = set.stream().map(item->item.getMessage()).collect(Collectors.joining(","));
        msg.substring(0,msg.length()-1);
        return Result.err(Result.CODE_ERR_SYS,msg);
    }
    //邦json沒綁好異常(post請求)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("參數不匹配",e);
        //獲取參數綁定結果(包括綁定錯誤信息)
        BindingResult bindingResult = e.getBindingResult();
        //獲取屬性錯誤集合
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        String errMsg = fieldErrorList.stream()
                .map(fieldError->fieldError.getField()+":"+fieldError.getDefaultMessage())
                .collect(Collectors.joining(","));
        return Result.err(Result.CODE_ERR_SYS,errMsg);
    }
    //綁普通字符串沒綁好異常
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e){
        log.error("參數不匹配",e);
        //獲取參數綁定結果(包括綁定錯誤信息)
        BindingResult bindingResult = e.getBindingResult();
        //獲取屬性錯誤集合
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        String errMsg = fieldErrorList.stream()
                .map(fieldError->fieldError.getField()+":"+fieldError.getDefaultMessage())
                .collect(Collectors.joining(","));
        return Result.err(Result.CODE_ERR_SYS,errMsg);
    }
}

三個注解:

①:Slf4j:lombok自帶的打印日志信息的一個注解,上面的log.error();就是方便程序員排查錯誤。

②:RestControllerAdvice:該注解說明本類是一個RestController的攔截器,還可以對controller處理方法添加額外邏輯,做增強處理(AOP的實現,try...catch...)

③:@ExceptionHandler:該注解說明本方法是一個異常處理器,即當被攔截的controller處理方法發生指定的異常時,即由本方法處理

三個異常:

①:ConstraintViolationException:get請求傳參不匹配

②:MethodArgumentNotValidException:post請求傳遞json串異常

③:BindException:get請求傳遞javaBean異常

除過這些,還有對自己定義異常的處理:

    //處理自定義系統異常
    @ExceptionHandler(SysException.class)
    public Result handleSysException(SysException e){
        log.error("系統錯誤",e);
        return Result.err(Result.CODE_ERR_SYS,"系統維護中");
    }
    //處理自定義業務異常
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e){
        return Result.err(Result.CODE_ERR_BUSINESS,e.getMessage());
    }
    //參數格式異常
    @ExceptionHandler(TypeMismatchException.class)
    public Result handleTypeMismatchException(TypeMismatchException e){
        log.error("系統錯誤",e);
        return Result.err(Result.CODE_ERR_BUSINESS,"系統維護中");
    }
    //處理遺留的異常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error("系統錯誤",e);
        return Result.err(Result.CODE_ERR_BUSINESS,"系統維護中");
    }

?

原文鏈接:https://blog.csdn.net/weixin_45836787/article/details/125915474

相關推薦

欄目分類
最近更新