網站首頁 編程語言 正文
目錄
場景再現:
怎么做?
遇到了什么問題?
怎么實現?
場景再現:
某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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-03-30 帶你了解Python妙開根號的三種方式_python
- 2022-09-05 Involution: Inverting the Inherence of Convolution
- 2022-08-10 python中ThreadPoolExecutor線程池和ProcessPoolExecutor進程
- 2022-11-04 ASP.NET?MVC解決上傳圖片臟數據的方法_實用技巧
- 2022-04-21 R語言繪制帶ErrorBar的分組條形圖代碼的分享_R語言
- 2022-10-28 React中使用react-file-viewer問題_React
- 2022-11-17 解讀Python中字典的key都可以是什么_python
- 2022-04-06 遠程過程調用RPC基本概念及實現原理_其它綜合
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支