SpringBoot校验
-
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
-
默认配置属性文件ValidationMessages.properties
# 可以写一些属性对 city.cityname.notnull=城市名不能为空 city.cityInitial.notnull=不为空哦 city.cityInitial.size=5
-
实体类加注解
package com.demo.entity; import org.hibernate.validator.constraints.Length; import org.springframework.context.annotation.PropertySource; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class City implements Serializable { private static final long serialVersionUID = -40142021265771170L; /** * 主键 自增长 */ private Integer id; /** * 城市名称 */ @NotNull(message = "{city.cityname.notnull}") private String cityName; /** * 城市名称拼音 */ private String cityNameSpell; /** * 城市首字母 */ @NotNull(message = "{city.cityInitial.notnull}") @Length(min = 1, max = 1, message = "{city.cityInitial.size}") private String cityInitial; }
-
方法参数加注解
@PostMapping("/add") public HttpResult add(@Validated City city){ return HttpResult.ok("保存城市信息成功"); }
如果出现乱码记得去设置都调成UTF-8