java - 覆盖 BindingResult 中的错误消息

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

我正在使用 Spring MVC 2.5 。

我有一些字段,其中数字只能被允许输入。我在用户界面上得到了我正在寻找的确切错误消息。类似的东西

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"

还有更好的想法吗?

最佳答案

尝试在消息属性文件中添加如下内容:

typeMismatch.objectClassName.field=您的自定义消息

就您而言:

typeMismatch.offerSetting.amount=您输入的字段价格金额无效

对我有用:)

关于java - 覆盖 BindingResult 中的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076142/

相关文章:

java - Windows Server 2008 Web Edition 配置让网站看到图像文件

java - 如何有效保管气钉中的 key ?

java - 在 AWT 中重写paintComponent

java - Spring中使用Map进行绑定(bind) - Thymeleaf

wpf - 当鼠标悬停在图像按钮上时如何更改图像按钮的颜色?

html - 如何使用 ngModel 在 div 的 innerhtml 属性上实现 2 路数据绑定(bind)?

java - 在双调数组中搜索变成无限循环

java - Spring-MVC 对 REST 客户端的验证响应

spring - Vaadin 和 Spring MVC 集成

winforms - ReportViewer 上的数据源为空