1.引入validation的依赖jar
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>3.2.3</version> </dependency>
2.请求报文增加字段的校验规则
package com.springweb.demo.request; import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data public class TestReq { @NotBlank(message = "请求字段不能为空!") private String reqText; }
3.使用注解@Valid启动校验
package com.springweb.demo.controller; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiSort; import com.springweb.demo.request.TestReq; import com.springweb.demo.respose.TestResp; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/validate") @ApiSort(2) @Tag(name = "报文校验功能") public class ValidateController { @PostMapping("/verify") @ResponseBody @Operation(summary = "请求报文校验", description = "报文校验示例", method = "POST") @ApiOperationSupport(order = 1) public TestResp verifyRequest(@Valid @RequestBody TestReq request){ TestResp resp = new TestResp(); String s = "hello, post method.[" + request.getReqText() + "]"; resp.setRespText(s); return resp; } }
标签:springboot,报文,校验,import,TestResp,validation,com From: https://www.cnblogs.com/wang-liang-blogs/p/18053978