Springboot2和Springboot3表单检验的区别

最近公司新项目决定使用Springboot3,由于之前没系统学习过Springboot3,所以表单验证还是使用Springboot2中做法,

1.引入依赖:

XML 复制代码
 <dependency>
	   <groupId>javax.validation</groupId>
	   <artifactId>validation-api</artifactId>
	   <version>2.0.1.Final</version>
 </dependency>

2.实体类导入依赖,检验规则引入的是javax.validation.constraints里面的包,比如NotBlank:

XML 复制代码
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.tehg.test.common.validation.ListValue;
import com.tehg.test.common.validation.group.AddGroup;
import com.tehg.test.common.validation.group.UpdateGroup;
import com.tehg.test.common.validation.group.UpdateStatusGroup;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;

import lombok.Data;


import java.io.Serializable;

/**
 * 品牌
 * 
 * @author 
 * @email
 * @date 2024-05-19 19:47:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@TableId
	@NotNull(message = "品牌id不能为空",groups = UpdateGroup.class)
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名称不能为空",groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotNull(groups = {AddGroup.class, UpdateGroup.class})
	@URL(message = "logo必须是一个合法有效的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@NotNull(groups = {AddGroup.class, UpdateStatusGroup.class})
	@ListValue(vals={0,1},groups = {AddGroup.class, UpdateStatusGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotNull(groups = {AddGroup.class, UpdateGroup.class})
	@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups={AddGroup.class,UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull
	@Min(value = 0,message = "排序必须大于等于0")
	private Integer sort;

}

3.controller中引入@Validated注解:

java 复制代码
    @RequestMapping("/save")
    public Result save(@Validated(AddGroup.class) @RequestBody BrandEntity brand){
        brandService.save(brand);
        return Result.success();
    }

4.引入全局异常处理:

java 复制代码
/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.whalehearing.tingyou.controller")
public class GlobalExceptionHandler {

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public Result handleValidExcepton(MethodArgumentNotValidException e){
        log.error("数据检验出现异常,异常类型{},异常信息:{}",e.getClass(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,Object> map=new HashMap<>();
        bindingResult.getFieldErrors().forEach(item ->{
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            map.put(field,defaultMessage);
        });
        return Result.error(ResultCodeEnum.VALID_EXCEPTION.getCode(),ResultCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value=Throwable.class)
    public Result handleUnknowExcepton(Throwable throwable){
        log.error("未知异常{}",throwable);
        Map<String,Object> map = new HashMap<>();
        map.put(ResultCodeEnum.UNKNOW_EXCEPTION.getCode().toString(),ResultCodeEnum.UNKNOW_EXCEPTION.getMessage());
        return Result.error(map);
    }

}

PS:上面只列出关键业务代码

然后启动测试,发现表单验证不生效,经多方查询后才知道,由于项目是使用Springboot3搭建的,在Springboot3中,JAVA JSR303检验需使用jakarta.validation.constraints里面的类,如果使用自己额外导入的validation-api里面的检验规则,将不会生效。

Springboot3中只需引入下面的依赖即可,版本替换为自己的Springboot版本:

XML 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
    <version>3.1.3</version>
</dependency>
相关推荐
黎宇幻生2 小时前
Java全栈学习笔记39
java·笔记·学习
jiangzhihao05152 小时前
前端自动翻译插件webpack-auto-i18n-plugin的使用
前端·webpack·node.js
Aurorar0rua2 小时前
C Primer Plus Notes 09
java·c语言·算法
嵌入式郑工3 小时前
LINUX驱动开发: 设备和驱动是怎么匹配的?
linux·运维·服务器
nongcunqq3 小时前
abap 操作 excel
java·数据库·excel
软件技术NINI4 小时前
html css网页制作成品——HTML+CSS盐津铺子网页设计(5页)附源码
前端·css·html
rain bye bye4 小时前
calibre LVS 跑不起来 就将setup 的LVS Option connect下的 connect all nets by name 打开。
服务器·数据库·lvs
郭式云源生法则4 小时前
归档及压缩、重定向与管道操作和综合使用,find精确查找、find处理查找结果、vim高级使用、vimdiff多文件使用
linux·运维·服务器
史迪奇_xxx4 小时前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_801252224 小时前
Java中的反射
java·开发语言