SpringBoot 开发实战 | 第四节 SpringBoot整合validation校验

本文介绍了如何在SpringBoot项目中集成Spring Validation进行数据校验,并通过FastJson处理异常返回,包括在UserController中使用@Validated注解、UserDTO的注解配置,以及定义全局异常处理类ExceptionResolver。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入jar包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.75</version>
</dependency>

2. 代码增加校验注解

UserController 的方法增加 @Validated 注解
@PostMapping("/user/save")
public Map<String,Object> save(@Validated  @RequestBody UserDTO user){
     Map<String,Object> map = new HashMap<>();
     map.put("code",200);
     map.put("data",mybatisPlusDemoService.save(user));
     return map;
 }

UserDTO增加@NotNull/@Max/@Min 一系列注解
@NotNull(message = "名称不能为空")
private String name;
/**
 * 年龄
 */
@NotNull(message = "年龄不能为空")
@Min(value = 20,message = "年龄必须大于20")
@Max(value = 100,message = "年龄必须小于100")
private Integer age;
/**
 * 性别
 */
@NotNull(message = "性别不能为空")
private Integer sex;

3. 增加异常拦截处理类ExceptionResolver

package com.leeong.demo.handler;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @author leeong
 */
@ControllerAdvice
@ResponseBody
public class ExceptionResolver {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ModelAndView resolveException(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
        if (e instanceof MethodArgumentNotValidException){
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("msg",((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage());
            fastJsonJsonView.setAttributesMap(map);
        }
        modelAndView.setView(fastJsonJsonView);
        return modelAndView;
    }
}

4. 接口调用和结果展示

在这里插入图片描述

5.总结

  1. 引入validatoin,fastjson jar包
  2. controller/dto 加入相关注解
  3. 定义错误统一拦截处理类

上一篇 mybatis-plus 分页、复杂条件查询
下一篇 SpringBoot整合SpringSecurity 入门篇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值