springboot validation 国际化
程序员文章站
2023-04-03 17:14:56
springbootvalidation国际化应用:验证注解属性message根据locale显示不同的信息**********************示例...
springboot validation 国际化
应用:验证注解属性message根据locale显示不同的信息
**********************
示例
**************
配置文件
application.yml
spring:
messages:
basename: messages/validation
**************
国际化文件
validation.properties
product.message.price="商品价格不能低于0.01"
validation.en_US.properties
product.message.price="price of product can not be less than 0.01"
validation.zh_CN.properties
product.message.price="商品价格不能低于0.01"
**************
pojo 层
Product
@Data
public class Product {
@NotBlank(message = "商品id不能为空")
private String productId;
@NotBlank(message = "商品名称不能为空")
private String productName;
@DecimalMin(value = "0.01",message = "{product.message.price}")
private Double price;
}
**************
config 层
WebConfig:配置验证器加载国际化属性文件
@Configuration
public class WebConfig {
@Resource
private MessageSource messageSource;
@Bean
public Validator initValidator(){
LocalValidatorFactoryBean validatorFactoryBean=new LocalValidatorFactoryBean();
validatorFactoryBean.setValidationMessageSource(messageSource);
return validatorFactoryBean;
}
}
**************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(@Validated Product product, BindingResult result){
System.out.println(product);
if (result.hasFieldErrors()){
result.getFieldErrors().forEach(error -> {
System.out.print("field:"+error.getField());
System.out.println(" ==> message:"+error.getDefaultMessage());
});
}
return "success";
}
}
**********************
使用测试
localhost:8080/hello?productId=1&productName=apple&price=0
默认输出
2020-07-15 18:41:42.456 INFO 5484 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-15 18:41:42.460 INFO 5484 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Product(productId=1, productName=apple, price=0.0)
field:price ==> message:"商品价格不能低于0.01"
设置 header:Accept-Language en-US,控制台输出:
Product(productId=1, productName=apple, price=0.0)
field:price ==> message:"price of product can not be less than 0.01"
国际化属性文件设置成功
本文地址:https://blog.csdn.net/weixin_43931625/article/details/107364360
推荐阅读
-
JavaScript面对国际化编程时的一些建议
-
springboot源码怎么看(springboot源码深度解析)
-
springboot配置tomcat配置乱码(配置乱码原因和对应解决法)
-
jQuery插件Validation表单验证详解
-
SpringBoot整合Elasticsearch7.2.0的实现方法
-
Springboot源码 TargetSource解析
-
Springboot源码 AbstractAdvisorAutoProxyCreator解析
-
解决Vue调用springboot接口403跨域问题
-
SpringBoot AOP方式实现多数据源切换的方法
-
SpringBoot war包部署到Tomcat服务器