最近公司新项目决定使用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>