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

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot不在使用@Validated 做參數校驗但是不想在Controller層怎么辦?

作者:桂亭亭 更新時間: 2023-07-04 編程語言

目錄

場景再現:

怎么做?

遇到了什么問題?

怎么實現?


場景再現:

某API接口接受加密的json字符串,接受字符串之后先進行解密處理,解密完成之后還要進行參數校驗處理,如果參數不合規范會直接返回提示信息。

怎么做?

我們完全可以中規中矩的,先在controller層接受字符串,然后解密,然后在serivce層參數校驗,但是這里有個問題,那就是解密后的json字符串將變成一個對象,然后這個對象中的字段卻十分的多幾十來個,如果使用普通的方法校驗,每個參數都需要一個if語句,那該是多磨的可怕呀!!所以我考慮借助Validated 輔助我進行參數校驗。

遇到了什么問題?

問題就是我們平常使用Validated 參數校驗是是直接在controller層進行校驗的比如這樣。

    @PostMapping("/resume-info")
    public ResponseResult<String>
    insertResumeInfo(@Validated(ValidatedGroup.Insert.class) @RequestBody ResumeMainInfoDTO dto) {
        return resumeInfoService.InsertInfo(dto);
    }
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResumeMainInfoDTO {

    @NotBlank(message = "!",groups = ValidatedGroup.Update.class)
    private Long id;

    /**
     * 姓名
     */
    @Length(max = 20,message ="!",groups = ValidatedGroup.Select.class)
    @NotBlank(message = "!",groups = ValidatedGroup.Insert.class)
    @NotBlank(message = "!",groups = ValidatedGroup.Update.class)
    private String userName;
}

我使用同樣的方式對service使用,但是失效了。那我們相對service層使用應該怎么做呀?

怎么實現?

controller層接受字符串參數,并轉換為對象



    @Autowired
    ss service;
    
@PostMapping("/getJson")
    public ResponseResult<String>  getJson(@RequestBody String dto) {
        RequestDTO requestDTO = JSON.parseObject(dto, RequestDTO.class);
        return service.startTask(requestDTO);
    }

?service層接口

    public ResponseResult<String> startTask(@Valid @RequestBody RequestDTO dto);

接口實現

@Validated
在當前類的頭上加上  

  @Override
    public ResponseResult<String> startTask(@Valid @RequestBody  RequestDTO dto) {
// 校驗完成后的其他代碼        
return start(dto);
    }

ok以上是關鍵的代碼,下面的不關鍵

注意關鍵部分

1 service層類上加上@Validated

2 被校驗的對象前加上@Valid @RequestBody(注意接口,以及接口的實現都要有)

3 在controller使用注入的方式調用即可

4 在dto里定義判斷校驗

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

部分dto代碼

    @Length(min = 1, max = 6, message = "申請類型不合法!提示:xx")
    String approve_type;
    // xx
    Integer port_type;

    @NotNull(message = "創建人id不能為空!")
//    @Range(min = 1,message = "創建人id不能為空!")
    Long create_user_id;
    @Length(max = 32, message = "創建人名稱過長!")
    String create_user_name;

全局異常處理

// 1:使用PathVariable并且是get請求的參數錯誤。
    // 2:使用RequestParam并且是from-data方式提交的post請求的參數錯誤。
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResult handleBindGetException(ConstraintViolationException e) {
        log.error("{}", e.getMessage(), e);
        List<String> defaultMsg = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return Params_Common_Res(defaultMsg);
    }


    // 錯誤情況:
    //1 使用了ResponseBody并且是json數據類型的post請求
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("{}", e.getMessage(), e);
        List<String> defaultMsg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(fieldError -> "【" + fieldError.getField() + "】" + fieldError.getDefaultMessage())
                .collect(Collectors.toList());
        return Params_Common_Res(defaultMsg);
    }

    /**
     * 兼容Validation校驗框架:忽略參數異常處理器
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("{}", e.getMessage(), e);
        log.error("ParameterName: {}", e.getParameterName());
        log.error("ParameterType: {}", e.getParameterType());
        return Params_Common_Res();
    }

    // 前端并沒有提交必要的參數信息
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResult error(HttpMessageNotReadableException e){
        log.error("{}", e.getMessage(), e);
        return ErrorResult.build(new ErrorResult( false,ErrorEnum.Params_Lack_Err.getMessage(),ErrorEnum.Params_Lack_Err.getCode()), e.getMessage());
    }

效果:

?

原文鏈接:https://blog.csdn.net/qq_53679247/article/details/131280759

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新