java后端進行參數校驗


利用注解的方式進行驗證前端傳入參數:
`
public class UavAddDto {
// import javax.validation.constraints.*;

@NotNull(message = "姓名不允許為null")
@NotEmpty(message = "姓名不允許為空,請檢查后重新重新傳入值")
public String name;

@NotNull(message = "傳入數據不允許為空")
@Min(value = 0, message = "傳入數據有誤,數據必須在 0~100之內")
@Max(value = 100, message = "傳入數據有誤,數據必須在 0~100之內")
public Integer count;

@Email(message = "傳入郵件格式有誤,請檢查")
public String email;

@Length(min = 11, max = 11, message = "傳入的電話號碼長度有誤,必須為11位")
public String mobile;

}
`

加上 @Valid 注解,開啟對傳入對象的驗證,不加該注解是無效的

`@RestController
public class UavController {

@Autowired
private UavService uavService;

@PostMapping("/add")
public String add(@RequestBody @Valid UavAddDto uavAddDto) {
    uavService.saveOne(uav);
    return "Success";
}

`

這里我們做全局的異常攔截,只將錯誤的信息返回給前端。
`@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor {

@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ExecutionResponse exceptionHandler(HttpServletRequest request, Exception e) {
    ExecutionResponse executionResponse = new ExecutionResponse();
    String failMsg = null;
    if (e instanceof MethodArgumentNotValidException) {
        // 拿到參數校驗具體異常信息提示
        failMsg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        executionResponse.setFailed(failMsg);
    }
    // 將消息返回給前端
    return executionResponse;
}

}
`
返回體:

`// 返回體 這里用了 lombok 插件
@Date
public class ExecutionResponse {

private Integer code = ResponseCodeEnum.RESPONSE_SUCCESS.code() ;

private String message = "操作成功";

public void setFailed(String message){
    this.code = ResponseCodeEnum.RESPONSE_FAILED.code();
    this.message = message;
}

}
`


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM