【问题标题】:Spring custom validation messageSpring 自定义验证消息
【发布时间】:2014-06-09 16:40:21
【问题描述】:

自定义验证消息不起作用。我有一个域类:

...
@RooJpaActiveRecord
public class Letter {

@NotNull(message="{validation.number_empty}")
@Size(min=1,max=20, message="{validation.number_size}")
@Column(length=20, nullable=false)
private String number;
...
}

/WEB-INF/i18n/messages.properties:

 #validation
 validation.number_size=number must be more than 1 and less than 20 symbols
 ...

我想在表单提交期间验证该域类中的一些字段。验证有效,但我收到输出消息:

{validation.number_size}

而不是预期的字符串:数字必须大于 1 且小于 20 个符号 在我项目的其他地方,我成功使用了来自属性文件的消息。

/WEB-INF/spring/webmvc-config.xml

 <bean     
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource" 
    id="messageSource" 
    p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" 
    p:fallbackToSystemLocale="false">
 </bean>

另外,我也试过了,但没有成功:

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="locations">
       <list>
         <value>classpath:WEB-INF/i18n/messages</value>
       </list>
     </property>
     <property name="ignoreUnresolvablePlaceholders" value="true"/>
     <property name="ignoreResourceNotFound" value="true"/>
 </bean>

【问题讨论】:

    标签: spring validation


    【解决方案1】:

    您需要一些额外的配置来使用您的 messageSource 自定义错误消息。

    尝试以下操作:

    /WEB-INF/spring/webmvc-config.xml:

    ...
    
    <bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
      <property name="validationMessageSource" ref="messageSource" />
    </bean>
    

    在你的控制器类中:

    ...
    
    import org.springframework.validation.Validator;
    
    ...
    
    @Autowired
    private Validator validator;
    
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
      binder.setValidator(validator);
    }
    

    有关详细信息,请参阅参考手册的this 部分。

    【讨论】:

    • 它为我节省了一天的时间。这个问题没有任何例外。你怎么解决这个问题?您是否经常阅读文档或阅读 Spring 框架的源代码或其他内容?
    • 我一般都是先看官方文档,再上网搜索。
    • 对于未使用 @component 注释的 RequestBody POJO 是否有效,即只是一个简单的包装类?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2014-05-31
    相关资源
    最近更新 更多