SpringBoot 如何使用 @RequestBody 进行数据校验

SpringBoot 如何使用 @RequestBody 进行数据校验

在 Web 开发中,前台向后台发送数据是非常常见的场景。而在 SpringBoot 框架中,我们通常使用 @RequestBody 注解来接收前台发送的 JSON 数据,并将其转化为 Java 对象。但是,接收到的数据并不一定是符合要求的,因此我们需要对其进行数据校验。本文将介绍如何在 SpringBoot 中使用 @RequestBody 进行数据校验。

在这里插入图片描述

什么是 @RequestBody

@RequestBody 注解用于接收前台发送的 JSON 数据,并将其转化为 Java 对象。它的作用是将 HTTP 请求正文中的 JSON 字符串绑定到相应的 Java 对象上。在 SpringBoot 中,我们通常使用 @RequestBody 注解来接收前台发送的 JSON 数据,并将其转化为 Java 对象。

如何使用 @RequestBody 进行数据校验

在 SpringBoot 中,我们可以使用 JSR-303 规范提供的注解来对 Java 对象进行数据校验。JSR-303 是 Java EE 6 中引入的 Bean Validation 规范,它提供了一套用于数据校验的注解。

在 SpringBoot 中使用 JSR-303 注解进行数据校验的步骤如下:

  1. 引入相关依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  1. 在 Java Bean 中添加校验注解

在 Java Bean 中添加校验注解,例如:

public class User {
    @NotNull(message = "用户名不能为空")
    private String username;

    @NotNull(message = "密码不能为空")
    @Size(min = 6, message = "密码长度不能小于 6 位")
    private String password;

    // 省略 getter 和 setter 方法
}
  1. 在 Controller 方法中添加 @Validated 和 @RequestBody 注解

在 Controller 方法中添加 @Validated 和 @RequestBody 注解,例如:

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/add")
    public Result addUser(@Validated @RequestBody User user) {
        // 处理添加用户的逻辑
    }
}

在上述代码中,@Validated 注解用于启用数据校验,@RequestBody 注解用于接收前台发送的 JSON 数据,并将其转化为 User 对象。

  1. 处理校验结果

如果数据校验失败,会抛出 MethodArgumentNotValidException 异常。我们可以在 ControllerAdvice 中捕获此异常,并返回校验结果。

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> errorMessages = new ArrayList<>();
        for (ObjectError error : allErrors) {
            errorMessages.add(error.getDefaultMessage());
        }
        return Result.error(String.join(",", errorMessages));
    }
}

在上述代码中,我们使用 @RestControllerAdvice 注解声明一个全局异常处理类,其中 @ExceptionHandler 注解用于捕获 MethodArgumentNotValidException 异常,并处理校验结果,最终返回一个 Result 对象。

完整代码示例

@Data
public class User {
    @NotNull(message = "用户名不能为空")
    private String username;

    @NotNull(message = "密码不能为空")
    @Size(min = 6, message = "密码长度不能小于 6 位")
    private String password;
}

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/add")
    public Result addUser(@Validated @RequestBody User user) {
        // 处理添加用户的逻辑
    }
}

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> errorMessages = new ArrayList<>();
        for (ObjectError error : allErrors) {
            errorMessages.add(error.getDefaultMessage());
        }
        return Result.error以上示例代码可能有些不完整,我们来完整展示一下如何使用 @RequestBody 进行数据校验的完整代码示例。

### 引入依赖

在 pom.xml 文件中添加以下依赖:

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

编写实体类

@Data
public class User {
    @NotNull(message = "用户名不能为空")
    private String username;

    @NotNull(message = "密码不能为空")
    @Size(min = 6, message = "密码长度不能小于 6 位")
    private String password;
}

编写 Controller

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/add")
    public Result addUser(@Validated @RequestBody User user) {
        // 处理添加用户的逻辑
    }
}

在上述代码中,@Validated 注解用于启用数据校验,@RequestBody 注解用于接收前台发送的 JSON 数据,并将其转化为 User 对象。

编写全局异常处理类

如果数据校验失败,会抛出 MethodArgumentNotValidException 异常。我们可以在 ControllerAdvice 中捕获此异常,并返回校验结果。

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> errorMessages = new ArrayList<>();
        for (ObjectError error : allErrors) {
            errorMessages.add(error.getDefaultMessage());
        }
        return Result.error(String.join(",", errorMessages));
    }
}

在上述代码中,我们使用 @RestControllerAdvice 注解声明一个全局异常处理类,其中 @ExceptionHandler 注解用于捕获 MethodArgumentNotValidException 异常,并处理校验结果,最终返回一个 Result 对象。

编写启动类

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void addUserTest() {
        User user = new User();
        user.setUsername("test");
        user.setPassword("12345");
        ResponseEntity<Result> responseEntity = restTemplate.postForEntity("/user/add", user, Result.class);
        Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
        Result result = responseEntity.getBody();
        Assert.assertEquals(ResultStatus.FAIL.getCode(), result.getStatus());
        Assert.assertEquals("密码长度不能小于 6 位", result.getMessage());
    }
}

在上述代码中,我们使用 SpringBoot 自带的 TestRestTemplate 对象来模拟发送 POST 请求,并验证数据校验的结果是否符合预期。

总结

在 SpringBoot 中使用 @RequestBody 进行数据校验,可以有效地提高代码的健壮性和可靠性。通过 JSR-303 提供的注解,我们可以轻松地对 Java 对象进行数据校验,并在数据校验失败时返回相应的错误信息。希望本文能够对大家在 SpringBoot 中使用 @RequestBody 进行数据校验有所帮助。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
首先,需要确定@RequestBody是用于绑定HTTP请求的HTTP请求主体(body)到方法参数或方法返回值上的注解。当使用@RequestBody注解时,SpringBoot会自动将处理程序方法参数绑定到HTTP请求主体中的JSON对象上。 如果@RequestBody的请求主体JSON为null,则有可能是请求的Content-Type与数据类型不匹配。例如,请求的Content-Type为application/json,但是请求体的格式不是JSON,或者请求体中的JSON格式存在问题,导致SpringBoot无法将其转换为对象。 解决这个问题需要按照以下步骤进行: 1. 确认请求主体是否为null,这可以通过在方法中打印日志或使用调试器进行调试来实现。 2. 确认请求头中的Content-Type是否与请求主体的数据格式相匹配。 3. 确认请求体中的JSON格式是否正确,可以使用JSON 校验工具确认。 4. 如果以上步骤均无法解决问题,则可以考虑使用自定义JSON反序列化器。 在自定义反序列化器中,可以通过添加注解@JsonDeserialize(using = CustomDeserializer.class)来指定自定义反序列化器。这样,在接收到JSON请求主体时,SpringBoot使用自定义反序列化器将JSON数据转换为Java对象。如果仍然无法解决问题,可以查看SpringBoot的日志文件,查找相关错误信息进行解决。 总之,当SpringBoot@RequestBody接收JSON为null时,需要仔细检查请求格式是否正确并考虑使用自定义反序列化器解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java老徐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值