spingboot 集成JSR303校验 和 spring实现分组校验

1、JSR303校验

1、依赖

		<!-- JSR303依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>

2、全局异常处理

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return ResultUtils.failure(errorMap.toString());
    }
}

3、使用判断字段不能为空


    @NotBlank(message = "订单号不能为空")
    @ApiModelProperty(value = "试用订单id" , name = "goodsUsageId")
    private String goodsUsageId;

4、直接使用@Valid注解

    @PostMapping("/addEvaluationRecord")
    @ApiOperation(value = "提交测评报告")
    public ResponseResult addEvaluationRecord(HttpServletRequest httpServletRequest, @Valid  @RequestBody EvaluationRecordAddModel evaluationRecordAddModel){
        String accountId = (String) httpServletRequest.getAttribute("accountId");
        if (StringUtils.isEmpty(accountId)) return ResultUtils.failure("用户id不存在");
        evaluationTemplateService.addEvaluationRecord(Integer.valueOf(accountId),evaluationRecordAddModel);
        return null;
    }

2、分组校验

1、创建修改分组接口UpdateGroup

package com.xihongshi.common.valid;

/**
 * 修改分组校验
 * @author mgq
 * @since 2021-03-29 11:24
 */
public interface UpdateGroup {
}

2、在类的属性上添加,groups = {UpdateGroup.class}

    @NotNull(message = "修改时,id不能为空",groups = {UpdateGroup.class})
    private Integer id;

3、在controller接口中加上@Validated(UpdateGroup.class)注解

注意:@Validated是spring提供的,可以实现校验的分组功能

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改收货地址信息")
    public ResponseResult update(HttpServletRequest httpServletRequest,@Validated(UpdateGroup.class) @RequestBody AccountAddressModel accountAddressModel){
        AccountAddress accountAddress = new AccountAddress();
        BeanUtils.copyProperties(accountAddressModel, accountAddress);
        String accountId = (String) httpServletRequest.getAttribute("accountId");
        QueryWrapper<AccountAddress> qw = new QueryWrapper<>();
        qw.eq("user_id",accountId);
        qw.eq("id",accountAddressModel.getId());
        accountAddress.setUserId(Integer.valueOf(accountId));
        boolean update = accountAddressService.update(accountAddress, qw);
        if (!update) {
            return ResultUtils.failure("修改数据失败");
        }
        return ResultUtils.success();
    }

猜你喜欢

转载自blog.csdn.net/qq_39564710/article/details/115235026
今日推荐