如何在Spring中使用批注验证,并从属性文件中获取错误消息? [英] How to use annotation validation in Spring with error message gotten from properties file?

查看:169
本文介绍了如何在Spring中使用批注验证,并从属性文件中获取错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的新手.

我在域类中这样设置验证:

public class Worker {

    @NotNull(message="Name must be input")
    @Size(min=1,max=50, message="Name must not exceed 50 characters")
    private String name;
...

}

这是jsp文件:

<form:input path="code" readonly="false" />
<font color="red"><form:errors path="code" />

以及控制器代码:

@RequestMapping(value="/test",method=RequestMethod.POST)
    public void form(@Valid Worker worker, BindingResult result) {

        if (result.hasErrors()) {
            return;
        }
...

它可以工作,但是如何在我的messageSource中用一些文本(例如worker.name.overflow)替换名称不能超过50个字符"?我是否需要在BindingResult中添加一个messageResolver?

所有搜索结果似乎都是关于编写自定义Validator类的,但是我现在想使用注释.我很确定有办法,因为在这个问题有人这样做了.

解决方案

要告诉休眠验证器对代码进行查找,请将message的值放在大括号中.例如,@NotNull(message="{worker.name.NotNull}",然后将转换内容放在类路径根目录的ValidationMessages.properties中. (/WEB-INF/classes,maven中的资源文件夹,等等.)

验证器实现独立地查找它们,它们继续在已经转换为默认消息的BindingResult上进行.发生在Spring消息源之外.从理论上讲,您可以重写LocalValidatorFactory bean,以将验证器的消息输出作为代码放置到Errors对象上,然后将括号保留在批注中,以便Hibernate Validator使其通过.将JSR-303 ConstraintViolations转换为spring Errors的源代码非常简单,可以读取和扩展.只是将注释的名称作为代码,注释的属性作为args,然后将验证程序的翻译作为默认消息.

可以在这里看到它: http://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/messageinterpolation/ResourceBundleMessageInterpolator.html

I'm a Spring newbie.

I set up validation in my domain class like this:

public class Worker {

    @NotNull(message="Name must be input")
    @Size(min=1,max=50, message="Name must not exceed 50 characters")
    private String name;
...

}

Here's the jsp file:

<form:input path="code" readonly="false" />
<font color="red"><form:errors path="code" />

And the controller code:

@RequestMapping(value="/test",method=RequestMethod.POST)
    public void form(@Valid Worker worker, BindingResult result) {

        if (result.hasErrors()) {
            return;
        }
...

It works, but how can I replace "Name must not exceed 50 characters" with some text (like worker.name.overflow) in my messageSource? May I need to add a messageResolver into BindingResult?

All the search result seems to say about writing a custom Validator class, but I want to use annotation for now. I'm pretty sure there's a way, because in this question someone has done that.

解决方案

To tell hibernate validator to do a lookup on a code put the value of message in braces. e.g., @NotNull(message="{worker.name.NotNull}" then put the translation in ValidationMessages.properties in the root of your classpath. (/WEB-INF/classes, resources folder in maven, etc.)

The validator implementation looks those up independently on its own, and they go on the BindingResult already translated as the default message. Happens outside of the Spring messagesource. You could in theory override LocalValidatorFactory bean to put the validator's message output onto the Errors object as the code and then leave the braces off in the annotation so that the Hibernate Validator passes it through. The source code that turns JSR-303 ConstraintViolations into spring Errors is simple enough to read and extend. It just puts the name of the annotation on as code, the annotation properties as args, and then the validator's translation as the default message.

Can see it here: https://src.springframework.org/svn/spring-framework/trunk/org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java

Edit for question in comment:

You can add a javax.validation.MessageInterpolator to your javax.validation.Configuration to tell it to look for messages in other properties files. If you're using the Spring LocalValidatorFactory bean it has a setMessageInterpolator on it that you can use to inject one.

For hibernate, the provider implementation is: http://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/messageinterpolation/ResourceBundleMessageInterpolator.html

这篇关于如何在Spring中使用批注验证,并从属性文件中获取错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆