在springBoot中hibernate-validator整合i18n国际化校验时一直出现乱码

发布于 2022-09-06 11:02:17 字数 3897 浏览 13 评论 0

在springBoot中整合i18n国际化校验时一直出现乱码,具体如下,不知该如何解决呢:

application.properties中配置的有:

spring.messages.basename=i18n/user/message

在resources下有i18n.user包
里面有i18n配置国际化的文件:
message.properties

user.content.name-can-not-be-empty=内容对象名称不能为空

message_zh_CN.properties

user.content.name-can-not-be-empty=内容对象名称不能为空

message_en_US.properties

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

现在在entity中添加校验注解,如

@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中传递时自动校验。
根据SpringBoot validator国际化随笔用过如下方法:

@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;  
    }  
}

但出来的一直是乱码格式:

"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容对象å\u0090\u008d称ä¸\u008dè\u0083½ä¸ºç©º', propertyPath=name, rootBeanClass=class com.entity.User, messageTemplate='${user.content.name-can-not-be-empty}'}\n]",

发现,乱码是使用resources下ValidationMessages.properties系列文件是产生的。

当使用i18n.user包中的文件时,若不在controller中的方法中添加 @Valid或@Validated的注解,则会报

"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;
    }

返回如下结果:

{
    "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": "内容对象名称不能为空",
            "objectName": "user",
            "field": "name",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Validation failed for object='user'. Error count: 1",
    "path": "/api/user"
}

有没有办法,让controller中的方法中不添加 @Valid或@Validated的注解时也能正确返回错误信息呢

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听风念你 2022-09-13 11:02:17

如果是检验的是对象的属性
可以封装一下方法(validator注入,你的bean是getValidator):

public static void validateWithException(Object object, Class<?>... groups) {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            Iterator iterator = constraintViolations.iterator();
            //取第一个错误抛出
            ConstraintViolation constraintViolation = (ConstraintViolation) iterator.next();
            throw new IllegalArgumentException(constraintViolation.getMessage());
        }

    }
    

当然也可以使用AOP的方式对请求方法进行校验。
对单个参数/多个参数,非对象的属性,则需要添加@Validated于类上,提前需配置MethodValidationPostProcessor bean

江心雾 2022-09-13 11:02:17

你的问题解决了吗,我也遇到了相同的问题

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文