如何自定义BigDecimal的默认消息 [英] How to customize default message for BigDecimal

查看:1482
本文介绍了如何自定义BigDecimal的默认消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是模型:

  public class myFormData {
private BigDecimal trackingNumber;

@有效
私人列表< myCustomRecord> records = new ArrayList< myCustomRecord>();
}

public class myCustomRecord {
//这个字段也出现在这里(对于子记录)
private BigDecimal trackingNumber;





$ b

我有一个控制器方法,它在某个时刻接收这个对象来进行保存。

  public @ResponseBody ValidationResponse save(模型模型,
@Valid myFormData formData,BindingResult结果,
HttpSession session){
// do stuff
}

如果一个字符串被传递到 trackingNumber 字段中,错误信息不好。


无法将'java.lang.String'类型的属性值转换为属性'records [0] .trackingNumber'所需的类型'java.math.BigDecimal';嵌套异常是java.lang.NumberFormatException



无法将类型为'java.lang.String'的属性值转换为所需类型为'java.math.BigDecimal'的属性'追踪号码';嵌套异常是java.lang.NumberFormatException

另一个潜在的复杂因素是我没有使用Spring表单,因为我试图做一些Ajax提交。这是我提交数据的方式:

 函数collectFormData(fields){
var data = {};

// myFormData
data [trackingNumber] =<<这里是某个值>>; (var i = 0; i data [records [+ i +]。trackingNumber] =<<<某值>

;取代;
//为子记录提交更多数据
}
返回数据;
}

var mData = collectFormData(aSelectedRows);
if(aSelectedRows.length> 0){
$ .post('call_controller_save',mData,function(response){
if(response.status ==='FAIL'){
displayError(response);
} else {
// SAVE SUCCESSFUL
$('#successMsgs')。append(Data Saved);
},' JSON');
}

我试着改变 trackingNumber 的数据类型为 String ,并写了一个自定义的 ConstraintValidator< CheckNumeric,String> 。它的窍门是...我可以通过 ValidationMessages.properties 来输入一条自定义消息,但是我想让这些模型符合预期的数据类型。 是否有另一种方法来控制错误信息并将其转化为好的和用户友好的?

(我也明白 NumberFormatException 最有可能发生在数据绑定之前,在验证步骤之前?但我仍不确定如何去修复默认消息)

编辑
我使用以下配置:

 < bean class = org.springframework.context.support.ResourceBundleMessageSource
id =messageSource>
< property name =basenames>
< list>
<值>讯息< /值>
< value> ValidationMessages< / value>
< / list>
< / property>
< / bean>

在每个属性文件中,我有相同的内容。

  formData.trackingNumber =格式无效

但是自定义消息仍然没有被拾起。 问题2:应该是 formData 还是 myFormData ?我对jsp页面上使用的表单对象的名称或名称感到困惑吗?

解决方案

添加到验证消息 - 如果Spring不能从提供的文本转换为数字,则默认使用这种格式:

  typeMismatch.java.math .BigDecimal =所需的格式是数字。 


Here are the models:

public class myFormData {
    private BigDecimal trackingNumber;

    @Valid
    private List<myCustomRecord> records = new ArrayList<myCustomRecord>();
}

public class myCustomRecord {
    //the field also appears here (for child records)
    private BigDecimal trackingNumber;
}

I have a controller method which receives this object at some point to do a save.

public @ResponseBody ValidationResponse save(Model model,
        @Valid myFormData formData, BindingResult result,
        HttpSession session){
       //do stuff
}

The problem I'm having is if a string is passed into the trackingNumber field, the error message is not nice.

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

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

One other potential complication is I'm not using Spring form since I'm trying to do some ajax submissions. This is how I'm submitting the data:

function collectFormData(fields) {
    var data = {};

    //myFormData
    data["trackingNumber"] = <<some value here>>;

    for (var i = 0; i < fields.length; i++) {
        data["records["+i+"].trackingNumber"] = <<some value>>; 
        //some more data to submit for child records
    }
    return data;
}

var mData = collectFormData(aSelectedRows);
if (aSelectedRows.length> 0) {
    $.post('call_controller_save', mData, function(response) {
     if (response.status === 'FAIL') {
         displayError(response);
     } else {
        //SAVE SUCCESSFUL
        $('#successMsgs').append("Data Saved");
    }, 'json');
} 

I've tried changing trackingNumber's data type to String and wrote a custom ConstraintValidator<CheckNumeric, String>. It does the trick... I can put in a custom message via ValidationMessages.properties, but I would like to keep the models true to the intended data type. Is there another way to control the error message and turn it into something nice and user friendly?

(I also understand the NumberFormatException is most likely happening in data binding, before the validation step? But I'm still not sure how to go about fixing the default message)

Edit I use the following configuration

<bean class="org.springframework.context.support.ResourceBundleMessageSource"
    id="messageSource">
    <property name="basenames">
        <list>
            <value>messages</value>
            <value>ValidationMessages</value>
        </list>
    </property>
</bean>

In each properties file, I have the identical content.

formData.trackingNumber=Invalid format

But the custom message is still not getting picked up. Question 2: Should it be formData or myFormData? I have confusion whether it is the class name or name of the form object used on the jsp page?

解决方案

Add to validation messages - this kind of format is used by default by Spring if it cannot convert from supplied text to number:

typeMismatch.java.math.BigDecimal=Required format is number.

这篇关于如何自定义BigDecimal的默认消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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