1,前端参数不可信,对于后端开发人员来说应该是一条铁律,所以对于前端参数的校验,必不可少,而统一的前端参数校验工具,对我们进行参数校验起到事半功倍的效果
2,统一参数校验工具ValidParamUtils
public class ValidParamUtils { public static void validInputParams(BindingResult bindingResult) throws ParameterValidErrorException { if(bindingResult.hasErrors()) { //如果对于字段的校验出现错误,抛出统一自定义参数异常 String errorMessage = ValidParamUtils.errorParamInfo(bindingResult); if (!StringUtils.isBlank(errorMessage)){ throw new ParameterValidErrorException(ErrorCode.BAD_REQUEST, errorMessage); } throw new ParameterValidErrorException(ErrorCode.BAD_REQUEST); } } public static String errorParamInfo(BindingResult bindingResult) { //从绑定结果中,获取错误信息 FieldError fe = bindingResult.getFieldError(); if(fe != null) { return fe.getDefaultMessage(); } ObjectError oe = bindingResult.getGlobalError(); if(oe != null) { return oe.getDefaultMessage(); } return ""; }
3,自定义参数异常
public abstract class ParamErrorException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; private ErrorCode errorCode; public BaseException() { } public BaseException(ErrorCode errorCode) { super(errorCode.getName()); this.errorCode = errorCode; } public BaseException(ErrorCode errorCode, String msg) { super(msg); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } public void setErrorCode(ErrorCode errorCode) { this.errorCode = errorCode; } }
4,使用自定义的统一参数校验工具
@PostMapping(value = "/manage/ads/theme/add") public Result addThemeActivity(@RequestBody @Validated(value = {AddOrUpdateThemeActivityRequest.AddThemeActivityGroup.class}) AddOrUpdateThemeActivityRequest addOrUpdateThemeActivityRequest, BindingResult bindingResult) { LOGGER.info("manage addThemeActivity param:{}", JSON.toJSONString(addOrUpdateThemeActivityRequest)); //参数校验 ValidParamUtils.validInputParams(bindingResult); Integer themeActivityNum = themeActivityService.selectThemeActivityByTitleAndId(addOrUpdateThemeActivityRequest.getTitle(), null); if (themeActivityNum > 0) { LOGGER.warn(String.format("%s. title:%s", ErrorCode.MANAGE_PROJECT_THEME_TITLE_EXIST.getName(), addOrUpdateThemeActivityRequest.getTitle())); return Result.builder().failed(ErrorCode.MANAGE_PROJECT_THEME_TITLE_EXIST).build(); } managerBannerService.insertThemeActivityInfo(addOrUpdateThemeActivityRequest); sendBizLog(addOrUpdateThemeActivityRequest.getTitle()); LOGGER.info("manage addThemeActivity success. "); return Result.builder().data("新增专题活动成功").success().build(); }
原文地址:https://www.cnblogs.com/webwangbao/p/9254245.html
时间: 2024-10-04 14:21:38