In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how springboot passes the parameter check @ Valid and how to catch its exception. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Pass parameter check @ Valid and catch its exception
Springboot parameters often need to be checked, for example, to create a file, the file name needs to be checked.
This article takes the creation of a folder as an example to verify the parameters: controller:
The first step is to add the annotation @ Valid in front of the parameter class that needs to be verified.
@ ApiOperation (value = "create a directory", notes = "create a new folder under a directory") @ ApiResponses ({@ ApiResponse (code = 500, response = RestCodeMsg.class, message = "error")}) @ PostMapping (value = "api/scene/createdir") public ResponseEntity createNewOrEditFile (@ RequestBody @ Valid ixviewVo ixveVo) {. / / Verification has nothing to do with content}
Secondly, check the parameter class:
@ Data@ApiModel@Getter@Setter@NoArgsConstructorpublic class ixviewVo {@ ApiModelProperty ("folder") private boolean dir @ NotBlank (message= "directory name cannot be empty") @ Pattern (regexp= "[^\\ s\\ /:\\ *\\?\"\ "\ |\.] * [^\\ s\ /:\\ *\"\ "\ |\] $", message= "directory name does not meet the standard") @ ApiModelProperty ("directory name") private String dirname @ ApiModelProperty ("parent directory ID") private Long parentId;}
Where [^\ s\\ /:\ *\?\ "\"\ |\.] * [^\\ s\ /:\\ *\\?\\ "\"\ |\.] $is the regular expression for file name verification. Copy it into the code and remove the automatically generated\.
At this point, all the settings for the parameter verification are complete. An exception is thrown when the parameter does not match the check. The next step is to catch the thrown exception:
@ RestControllerAdvicepublic class BadRequestExceptionHandler {private static final Logger logger = LoggerFactory.getLogger (BadRequestExceptionHandler.class); @ ExceptionHandler (MethodArgumentNotValidException.class) public ResponseEntity validationBodyException (MethodArgumentNotValidException exception) {BindingResult result = exception.getBindingResult (); if (result.hasErrors ()) {List errors = result.getAllErrors (); errors.forEach (p-> {FieldError fieldError = (FieldError) p Logger.error ("Data check failure: object {" + fieldError.getObjectName () + "}, field {" + fieldError.getField () + "}, errorMessage {" + fieldError.getDefaultMessage () + "}");} return ResponseEntity.ok (getPublicBackValue (false, "directory name does not meet the standard")) } public Map getPublicBackValue (boolean flag, String message) {Map map = new HashMap (); if (flag) {map.put ("result_code", 0);} else {map.put ("result_code", 1);} map.put ("result_reason", message); return map }} @ Valid check exception catch @ Api (tags = {"parameter management"}) @ Validated@RestController@RequestMapping ("/ module/param") public class TbModuleParamController {} public ResponseDTO getModuleParam (@ PathVariable (name = "moduleId") @ Valid @ NotNull @ Max (value = 13) @ Min (value = 1) Integer moduleId) {QueryWrapper paramQueryWrapper = new QueryWrapper (); paramQueryWrapper.eq ("module_id", moduleId) .eq ("state", 1) TbModuleParam moduleParam = moduleParamService.getOne (paramQueryWrapper); List queryParamVoList = new ArrayList (); if (moduleParam! = null) {queryParamVoList = JSONArray.parseArray (moduleParam.getModuleJson (), QueryParamVo.class);} return ResponseDTO.defaultResponse (queryParamVoList);} @ PostMapping (value = "/ save", produces = WebServiceCommonConstant.PRODUCES_JSON) public ResponseDTO addDict (@ RequestBody @ Validated LandInfoBasicVo saveVo) {boolean result = landInfoService.saveInfo (saveVo) Return ResponseDTO.defaultResponse ("saved successfully");} @ NotBlank (message = "Land name cannot be empty") @ Size (max = 1) private String landName;@ControllerAdvicepublic class ExceptionHandle {private static final Logger logger = LoggerFactory.getLogger (ExceptionHandle.class); public static List msgList = new ArrayList () / * * exception handling * * @ param e exception information * @ return return class is my custom API return class. The parameters are the return code and the return result. The return result of the exception is an empty string * / @ ExceptionHandler (value = Exception.class) @ ResponseBody public ResponseDTO handle (Exception e) {/ / Custom exception returns the corresponding code if (e instanceof PermissionException) {PermissionException ex = (PermissionException) e Return ResponseDTO.customErrorResponse (ex.getCode (), ex.getMessage ());} / / Information corresponding to other exception reports else {logger.info ("[system exception] {}", e.getMessage (), e); msgList.clear (); msgList.add (e.toString ()); StackTraceElement [] stackTrace = e.getStackTrace () For (StackTraceElement element: stackTrace) {msgList.add (element.getClassName () + ":" + element.getMethodName () + "," + element.getLineNumber ());} return ResponseDTO.customErrorResponse (- 1, "system internal error") } @ ExceptionHandler (value = MethodArgumentNotValidException.class) @ ResponseBody public ResponseDTO handleMethodArgumentNotValidException (MethodArgumentNotValidException ex) {List message = new ArrayList (); if (ex.getBindingResult ()! = null) {for (FieldError item: ex.getBindingResult (). GetFieldErrors ()) {String itemMessage = item.getDefaultMessage (); message.add (itemMessage) }} return ResponseDTO.customErrorResponse (- 1, message.toString () .replace ("[", ") .replace ("] ","));} @ ExceptionHandler (value = ConstraintViolationException.class) @ ResponseBody public ResponseDTO handleConstraintViolationException (ConstraintViolationException ex) {List message = new ArrayList (); Set
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.