Spring Boot 参数注解校验

本文介绍了如何在SpringBoot的Controller和Service层利用注解进行参数校验,包括单参数校验和引用类型参数校验。通过@Validated和@Valid注解,可以有效地确保请求参数的正确性和完整性,提高代码的健壮性。
摘要由CSDN通过智能技术生成

项目backend模块Controller层和api模块service层使用注解校验
1、校验单参数

  • 在对应类上加@Validated注解
  • 在接口参数上添加校验注解
    注意是在类上添加@Validated
@RestController
@Validated
public class ResourceController extends BaseController {
    @GetMapping("/resourceCenter/paper/analyseByDifficulty")
    public List<DifficultyAnalyseInfo> analyseByDifficulty(@NotNull(message = "paperId不能为空") Long paperId) {
        return resourceCenterService.analyseByDifficulty(paperId);
    }
}
@FeignClient(name = "cloud-aital-resource-svc", decode404 = true, url = "${feign.url.cloud-aital-resource-svc:}")
@Validated
public interface ResourceService {
    @GetMapping("/resource/file")
    ApiResult<EcpFileDTO> getResourceFile(@NotNull(message = "fileId不能为空") Long fileId);
}

2、对引用类型(封装参数对象)参数校验

  • 在对象参数需要校验的属性上添加校验注解
  • 在接口参数上添加@Valid注解
public class HtmlDownloadRequest implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 下载html代码
     */
    @NotBlank(message = "html不能为空!")
    private String html;
    /**
     * 下载文件类型,pdf,docx
     */
    @NotBlank(message = "fileType不能为空!")
    private String fileType;
    /**
     * 业务id
     */
    @NotNull(message = "业务id不能为空!")
    private Long id;
    /**
     * 对象或集合属性级联校验需要加@Valid注解
     */
    @Valid
    private EcpFileDTO files;
}
@PostMapping("/resourceCenter/downloadQuestionOrPaper")
public EcpFileDTO downloadQuestionOrPaper(@RequestBody @Valid HtmlDownloadRequest request) {
    return resourceCenterService.getHtmlDownloadUrl(request);
}

常见的注解校验
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值