在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java  網(wǎng)絡(luò)安全/ 在springBoot中hibernate-validator整合i18n國(guó)際化

在springBoot中hibernate-validator整合i18n國(guó)際化校驗(yàn)時(shí)一直出現(xiàn)亂碼

在springBoot中整合i18n國(guó)際化校驗(yàn)時(shí)一直出現(xiàn)亂碼,具體如下,不知該如何解決呢:

application.properties中配置的有:

spring.messages.basename=i18n/user/message

在resources下有i18n.user包
里面有i18n配置國(guó)際化的文件:
message.properties

user.content.name-can-not-be-empty=內(nèi)容對(duì)象名稱(chēng)不能為空

message_zh_CN.properties

user.content.name-can-not-be-empty=內(nèi)容對(duì)象名稱(chēng)不能為空

message_en_US.properties

user.content.name-can-not-be-empty=content object's name can not be empty

現(xiàn)在在entity中添加校驗(yàn)注解,如

@Entity
@Table(name = "user")
@Inheritance(strategy = InheritanceType.JOINED)
@DynamicInsert
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull(message = "{user.content.name-can-not-be-empty}")
    private String name;
}

想control中傳遞時(shí)自動(dòng)校驗(yàn)。
根據(jù)SpringBoot validator國(guó)際化隨筆用過(guò)如下方法:

@Configuration
public class ValidatorConfiguration {
    public ResourceBundleMessageSource getMessageSource() throws Exception {  
        ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();  
        rbms.setDefaultEncoding("UTF-8");  
        rbms.setBasenames("i18n/user/message");  
        return rbms;  
    }  
  
    @Bean  
    public Validator getValidator() throws Exception {  
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();  
        validator.setValidationMessageSource(getMessageSource());  
        return validator;  
    }  
}

但出來(lái)的一直是亂碼格式:

"message": "Validation failed for classes [com.entity.User] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='$?\u0086\u0085??1?ˉ1è±??\u0090\u008d?§°??\u008dè\u0083???o??o', propertyPath=name, rootBeanClass=class com.entity.User, messageTemplate='${user.content.name-can-not-be-empty}'}\n]",

發(fā)現(xiàn),亂碼是使用resources下ValidationMessages.properties系列文件是產(chǎn)生的。

當(dāng)使用i18n.user包中的文件時(shí),若不在controller中的方法中添加 @Valid或@Validated的注解,則會(huì)報(bào)

"message": "Validation failed for classes [com.entity.User] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='{user.content.name-can-not-be-empty}', propertyPath=name, rootBeanClass=class com.entity.User, messageTemplate='{user.content.name-can-not-be-empty}'}\n]",

存在注解如:

    @PutMapping(value = "")
    public User create( @RequestBody() @Valid User user) {
        user= userService.save(user);
        return user;
    }

返回如下結(jié)果:

{
    "timestamp": 1516010929111,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
    "errors": [
        {
            "codes": [
                "NotNull.user.name",
                "NotNull.name",
                "NotNull.java.lang.String",
                "NotNull"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                }
            ],
            "defaultMessage": "內(nèi)容對(duì)象名稱(chēng)不能為空",
            "objectName": "user",
            "field": "name",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Validation failed for object='user'. Error count: 1",
    "path": "/api/user"
}

有沒(méi)有辦法,讓controller中的方法中不添加 @Valid或@Validated的注解時(shí)也能正確返回錯(cuò)誤信息呢

回答
編輯回答
菊外人

如果是檢驗(yàn)的是對(duì)象的屬性
可以封裝一下方法(validator注入,你的bean是getValidator):

public static void validateWithException(Object object, Class<?>... groups) {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            Iterator iterator = constraintViolations.iterator();
            //取第一個(gè)錯(cuò)誤拋出
            ConstraintViolation constraintViolation = (ConstraintViolation) iterator.next();
            throw new IllegalArgumentException(constraintViolation.getMessage());
        }

    }
    

當(dāng)然也可以使用AOP的方式對(duì)請(qǐng)求方法進(jìn)行校驗(yàn)。
對(duì)單個(gè)參數(shù)/多個(gè)參數(shù),非對(duì)象的屬性,則需要添加@Validated于類(lèi)上,提前需配置MethodValidationPostProcessor bean

2018年1月23日 07:22