参考
基础知识
基于案例: SpringBoot-jsr303 参数校验
添加资源包
resources
-新建
-资源包
资源捆绑包基名称
-默认为ValidationMessages
,不可更改要添加区域的设置
-+
-zh_CN
,en_US
- 自动添加了 3 个文件
点击
ValidationMessages.properties
-选择左下角资源包
-点击左上角+
新增下面几个变量
变量名称 | ValidationMessages.properties(//) ValidationMessages.properties(中文/中国/) | ValidationMessages.properties(英语/美国/) |
---|---|---|
id.notnull |
id 不能为空 | id not can null |
name.notblanck |
name 不能为空 | name not can null |
name.length |
name [${validatedValue}] 长度应在 {min}-{max} 之间 | name [${validatedValue}] length is {min}-{max} between |
createDate.notnull |
创建日期不能为空 | create Date not null |
amount.notnull |
金额不能为空 | amount not is null |
新增实体类-Shop
package com.atguigu.web.model;
import com.atguigu.web.valid.AddGroup;
import com.atguigu.web.valid.ArrayVal;
import com.atguigu.web.valid.UpdateGroup;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
public class Shop {
@NotNull(message = "{id.notnull}")
private Long id;
@NotBlank(message = "{name.notblanck}")
@Length(min = 2, max = 19, message = "{name.length}")
private String name;
@NotNull(message = "{createDate.notnull}")
private LocalDate createDate;
@NotNull(message = "{amount.notnull}")
private BigDecimal amount;
}
新增接口
package com.atguigu.web.controller;
import com.atguigu.web.model.Shop;
import com.atguigu.web.utils.CommonUtils;
import com.atguigu.web.valid.AddGroup;
import com.atguigu.web.valid.UpdateGroup;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping("/valid1")
public String valid1(@RequestBody @Validated Shop param) {
return "OK";
}
}
测试
zh-CN 的情况
Header
中Accept-Language
设置为zh-CN
Body
{
"id":"",
"name":"a",
"createDate":"",
"amount": "",
"isDelete": 0
}
- 返回
name:name [a] 长度应在 2-19 之间;id:id 不能为空;createDate:创建日期不能为空;amount:金额不能为空
en-US 的情况
Header
中Accept-Language
设置为en-US
Body
{
"id":"",
"name":"a",
"createDate":"",
"amount": "",
"isDelete": 0
}
- 返回
createDate:create Date not null;name:name [a] length is 2-19 between;amount:amount not is null;id:id not can null
自定义资源包
新建资源包 Resources/static/message
- 新增下面几个变量
变量名称 | ValidationMessages.properties(//) ValidationMessages.properties(中文/中国/) | ValidationMessages.properties(英语/美国/) |
---|---|---|
userName.notnull |
用户名不能为空 | userName not is null |
email.notnull |
电子邮件不能为空 | email not is null |
配置文件修改资源目录位置
#设置本地语言为zh_CN
#spring.web.locale=zh_CN
#指定编码格式
spring.messages.encoding=UTF-8
#国际化文件位置
spring.messages.basename=static/message
#配置缓存的时间,单位 s
#spring.messages.cache-duration=10
新建配置类-WebMvcConfig
package com.atguigu.web.config;
import jakarta.annotation.Resource;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 自定义国际化参数校验提示资源文件路径
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Resource
private MessageSource messageSource;
@Override
public Validator getValidator() {
return validator();
}
@Bean
public Validator validator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource);
return validator;
}
}
新建测试类-Person
package com.atguigu.web.model;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class Person {
private Long id;
@NotBlank(message = "{userName.notnull}")
private String userName;
@NotBlank(message = "{email.notnull}")
private String email;
private Integer age;
public Person(){}
public Person(Long id, String userName, String email, Integer age) {
this.id = id;
this.userName = userName;
this.email = email;
this.age = age;
}
}
新建测试方法-valid2
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping(value ="/valid2", produces = "text/html;charset=utf-8" , method = RequestMethod.POST)
public String valid2(@RequestBody @Validated Person param, BindingResult result) {
if(result.hasErrors()) {
List<String> list = new ArrayList<>();
List<FieldError> fieldErrors = result.getFieldErrors();
fieldErrors.forEach(item -> {
String field = item.getField();
String defaultMessage = item.getDefaultMessage();
list.add(field + "-" + defaultMessage);
});
String msg = String.join(";",list);
return msg;
}
return "OK";
}
}
测试-zh-CN 的情况
{
"id":1,
"userName":"",
"email":"",
"age": 10
}
Header
中Accept-Language
设置为zh-CN
返回
email-电子邮件不能为空;userName-用户名不能为空
测试-en-US 的情况
{
"id":1,
"userName":"",
"email":"",
"age": 10
}
Header
中Accept-Language
设置为en-US
返回
userName-userName not is null;email-email not is null