SpringBoot-jsr303 参数校验-国际化

2023年12月13日 10:23 · 阅读(142) ·

参考

【java工程师必知】SpringBoot Validation入参校验国际化

基础知识

基于案例: SpringBoot-jsr303 参数校验

添加资源包

  • resources-新建-资源包

  • 资源捆绑包基名称-默认为 ValidationMessages,不可更改
  • 要添加区域的设置-+-zh_CNen_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

  1. package com.atguigu.web.model;
  2. import com.atguigu.web.valid.AddGroup;
  3. import com.atguigu.web.valid.ArrayVal;
  4. import com.atguigu.web.valid.UpdateGroup;
  5. import jakarta.validation.constraints.NotBlank;
  6. import jakarta.validation.constraints.NotNull;
  7. import lombok.Data;
  8. import org.hibernate.validator.constraints.Length;
  9. import java.math.BigDecimal;
  10. import java.time.LocalDate;
  11. @Data
  12. public class Shop {
  13. @NotNull(message = "{id.notnull}")
  14. private Long id;
  15. @NotBlank(message = "{name.notblanck}")
  16. @Length(min = 2, max = 19, message = "{name.length}")
  17. private String name;
  18. @NotNull(message = "{createDate.notnull}")
  19. private LocalDate createDate;
  20. @NotNull(message = "{amount.notnull}")
  21. private BigDecimal amount;
  22. }

新增接口

  1. package com.atguigu.web.controller;
  2. import com.atguigu.web.model.Shop;
  3. import com.atguigu.web.utils.CommonUtils;
  4. import com.atguigu.web.valid.AddGroup;
  5. import com.atguigu.web.valid.UpdateGroup;
  6. import org.springframework.validation.BindingResult;
  7. import org.springframework.validation.FieldError;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. @RestController
  14. @RequestMapping("/test")
  15. public class TestController {
  16. @PostMapping("/valid1")
  17. public String valid1(@RequestBody @Validated Shop param) {
  18. return "OK";
  19. }
  20. }

测试

zh-CN 的情况

  1. {
  2. "id":"",
  3. "name":"a",
  4. "createDate":"",
  5. "amount": "",
  6. "isDelete": 0
  7. }
  • 返回
  1. name:name [a] 长度应在 2-19 之间;id:id 不能为空;createDate:创建日期不能为空;amount:金额不能为空

en-US 的情况

  1. {
  2. "id":"",
  3. "name":"a",
  4. "createDate":"",
  5. "amount": "",
  6. "isDelete": 0
  7. }
  • 返回
  1. createDate:create Date not null;name:name [a] length is 2-19 between;amount:amount not is null;id:id not can null

自定义资源包

参考:SpringBoot 国际化配置参数校验请求头传参(二)

新建资源包 Resources/static/message

  • 新增下面几个变量
变量名称 ValidationMessages.properties(//)
ValidationMessages.properties(中文/中国/)
ValidationMessages.properties(英语/美国/)
userName.notnull 用户名不能为空 userName not is null
email.notnull 电子邮件不能为空 email not is null

配置文件修改资源目录位置

  1. #设置本地语言为zh_CN
  2. #spring.web.locale=zh_CN
  3. #指定编码格式
  4. spring.messages.encoding=UTF-8
  5. #国际化文件位置
  6. spring.messages.basename=static/message
  7. #配置缓存的时间,单位 s
  8. #spring.messages.cache-duration=10

新建配置类-WebMvcConfig

  1. package com.atguigu.web.config;
  2. import jakarta.annotation.Resource;
  3. import org.springframework.context.MessageSource;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.validation.Validator;
  7. import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
  9. /**
  10. * 自定义国际化参数校验提示资源文件路径
  11. */
  12. @Configuration
  13. public class WebMvcConfig extends WebMvcConfigurationSupport {
  14. @Resource
  15. private MessageSource messageSource;
  16. @Override
  17. public Validator getValidator() {
  18. return validator();
  19. }
  20. @Bean
  21. public Validator validator() {
  22. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  23. validator.setValidationMessageSource(messageSource);
  24. return validator;
  25. }
  26. }

新建测试类-Person

  1. package com.atguigu.web.model;
  2. import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
  3. import jakarta.validation.constraints.NotBlank;
  4. import jakarta.validation.constraints.NotNull;
  5. import lombok.Data;
  6. @Data
  7. public class Person {
  8. private Long id;
  9. @NotBlank(message = "{userName.notnull}")
  10. private String userName;
  11. @NotBlank(message = "{email.notnull}")
  12. private String email;
  13. private Integer age;
  14. public Person(){}
  15. public Person(Long id, String userName, String email, Integer age) {
  16. this.id = id;
  17. this.userName = userName;
  18. this.email = email;
  19. this.age = age;
  20. }
  21. }

新建测试方法-valid2

  1. @RestController
  2. @RequestMapping("/test")
  3. public class TestController {
  4. @RequestMapping(value ="/valid2", produces = "text/html;charset=utf-8" , method = RequestMethod.POST)
  5. public String valid2(@RequestBody @Validated Person param, BindingResult result) {
  6. if(result.hasErrors()) {
  7. List<String> list = new ArrayList<>();
  8. List<FieldError> fieldErrors = result.getFieldErrors();
  9. fieldErrors.forEach(item -> {
  10. String field = item.getField();
  11. String defaultMessage = item.getDefaultMessage();
  12. list.add(field + "-" + defaultMessage);
  13. });
  14. String msg = String.join(";",list);
  15. return msg;
  16. }
  17. return "OK";
  18. }
  19. }

测试-zh-CN 的情况

  1. {
  2. "id":1,
  3. "userName":"",
  4. "email":"",
  5. "age": 10
  6. }
  • HeaderAccept-Language 设置为 zh-CN

  • 返回

  1. email-电子邮件不能为空;userName-用户名不能为空

测试-en-US 的情况

  1. {
  2. "id":1,
  3. "userName":"",
  4. "email":"",
  5. "age": 10
  6. }
  • HeaderAccept-Language 设置为 en-US

  • 返回

  1. userName-userName not is null;email-email not is null