【问题标题】:Override error messages in BindingResult覆盖 BindingResult 中的错误消息
【发布时间】:2013-06-09 04:38:52
【问题描述】:

我正在使用 Spring MVC 2.5。

我有数字应该只允许输入的字段。我在我正在寻找的 UI 上收到了确切的错误消息。像

Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException

我不想向用户显示那种消息。我确实使用 message.properties 文件来组织要显示的文本。

我唯一需要的是我想覆盖特定字段的错误消息。我不能这样做,但这是我使用的技巧

if(result.hasFieldErrors()){

            List<FieldError> bindingErrors=( List<FieldError>)result.getFieldErrors();
            BindingResult fieldErrors=new BeanPropertyBindingResult (offerSetting, "offerSetting");
            for(FieldError error :bindingErrors ){
                String field=error.getField();                
                fieldErrors.rejectValue(field, "invalid.amount."+field);


            }


            result=fieldErrors;
            #more code

我正在做的是创建 BeanPropertyBindingResult,它是 BindingResult 的实现,并用我想要的消息填充错误字段,并将引用传递给结果对象,以便显示。但是,我现在收到两个默认消息

like

Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException

还有我想要的信息。类似的东西

"The amount for field price you entered is invalid"

有更好的想法吗?

【问题讨论】:

  • 以前从未这样做过,但也许您可以在绑定类中添加 try catch?
  • @DanielRobertus 看看下面选择的答案

标签: java spring-mvc data-binding error-handling


【解决方案1】:

尝试添加到您的消息属性文件中,如下所示:

typeMismatch.objectClassName.field=Your custom message

在你的情况下:

typeMismatch.offerSetting.amount=The amount for field price you entered is invalid

为我工作:)

【讨论】:

  • 甜蜜!!!你让我在早上很开心。我无法想象我的一天会变成什么样子。 :D
  • 我认为将 prop 文件注册也包含在 servlet.xml 文件中会很有帮助。
猜你喜欢
  • 2019-07-18
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 2014-04-07
  • 2011-07-15
  • 1970-01-01
相关资源
最近更新 更多