SpringBoot validator国际化随笔

最近接触到使用SpringBoot提供一个web服务,需要对request的中的请求的数据进行校验

一、使用
dto 中有一个职位属性,添加非空和长度的校验
CampusPlanDTO:
    @NotEmpty(message = "校招职位名称为空")
    @Length(min = 2, max = 5, message = "职位名称超过长度需要在{min}-{max}之间")
    private String positionName;
    @valid
    private Object obj;
controller 接收请求时:
   @RequestMapping(value = "/feign/queryList", method = RequestMethod.POST)
    public JsonResult<?> queryList(@Valid @RequestBody CampusPlanDTO campusPlanDTO,
            BindingResult result) {
//result 中包含校验的错误信息,
}
如果dto中属性为其它自定义类,在属性上面加@valid,会对依赖的属性校验。

二、国际化:
需要将错误信息放在配置文件中,将上面的注解换成
 @NotEmpty(message = "{position.name.null}")
     @Length(min = 2, max = 5, message = "{position.name.length}")
在resources 下面增加 ValidationMessages_zh_CN.properties,内容
 position.name.null = 校招职位名称为空
    position.name.length = 职位名称超过长度需要在{min}-{max}之间
注意:这里的properties文件在我的eclipse不能直接写中文,直接写中文的话,程序读出来时乱码,后面使用propertiesEditor 插件可以解决中文乱码的问题

三、更改ValidationMessages_zh_CN.properties 文件的名称和路径。
在Springboot 对应的Appliaction 中增加如下代码:
public ResourceBundleMessageSource getMessageSource() throws Exception {
        ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
        rbms.setDefaultEncoding("UTF-8");
        rbms.setBasenames("i18n/errors/ErrorMessages", "i18n/prompt/PromptMessages",
                "i18n/validation/ValidationMessages");
        return rbms;
    }

    @Bean
    public Validator getValidator() throws Exception {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(getMessageSource());
        return validator;
    }

简单的跟了一下代码
LocalValidatorFactoryBean.afterPropertiesSet() 方法中有
if (targetInterpolator == null) {
targetInterpolator = configuration.getDefaultMessageInterpolator();
}
configurationimpl.getDefaultMessageInterpolator() 里面将配置文件指定在resource 下面




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值