springboot validation 国际化
程序员文章站
2022-05-18 17:48:22
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
上一篇: 点击按钮下滑显示组件