类型不匹配消息的春季用法


问题内容

我已经在网络上和stackoverflow中进行了一些搜索,以查看如何处理在一个屏幕上收到的以下消息:

无法将[qtyToShip]属性的[java.lang.String]类型的属性值转换为所需的[java.lang.Long]类型;嵌套异常为java.lang.IllegalArgumentException:无法解析数字:无法解析的数字:“
a”

通过研究和查看网络,我假定将以下内容添加到我的errors.properties文件中将产生所需的结果:

typeMismatch.shippingCommand.qtyToShip=1. Invalid value for Qty To Ship, accepts only numbers.  
typeMismatch.qtyToShip=2. Invalid value for Qty To Ship, accepts only numbers. 
shippingCommand.qtyToShip=3. Invalid value for Qty To Ship, accepts only numbers. 
qtyToShip=4. Invalid value for Qty To Ship, accepts only numbers.


typeMismatch.java.lang.NumberFormatException=5. Invalid value for {0}, accepts only numbers. 
typeMismatch.java.lang.Integer=Must specify an integer value. 
typeMismatch.java.lang.Long=Must specify an integer value. 
typeMismatch.java.lang.Float=Must specify a decimal value. 
typeMismatch.java.lang.Double=Must specify a decimal value.  
typeMismatch.int=Invalid number entered 
typeMismatch=Invalid type entered

我将整数值添加到消息中,以确定将显示哪个值。

现在,在我的JSP顶部,我有以下内容:

  <center>
    <spring:hasBindErrors name="shippingCommand">
      <c:if test="${errors.errorCount > 0 }">
        <h4>Following errors need to be corrected:</h4>
        <font color="red">
          <c:forEach items="${errors.allErrors}" var="error">
            <spring:message code="${error.code}" arguments="${err.arguments}" text="${error.defaultMessage}"/><br />
          </c:forEach>
        </font>
      </c:if>
    </spring:hasBindErrors>
  </center>

上面是我的表格以外,我的表格内有以下内容(测试理想情况)

因此,结果是,当我运行代码以触发错误时,我看到在窗体内部收到以下消息:

1. Invalid value for Qty To Ship, accepts only numbers.

这来自于此:typeMismatch.shippingCommand.qtyToShip

表单的外部显示:

Invalid type entered

我不明白的是为什么我可以在表单内部显示正确的消息,但不能在表单外部显示?

在控制器中,我添加了以下内容:

@Override
protected void initBinder(HttpServletRequest pRequest, ServletRequestDataBinder pBinder) throws Exception
{
    NumberFormat numberFormat = NumberFormat.getInstance();
    pBinder.registerCustomEditor(Long.class, "qtyToShip", new CustomNumberEditor(Long.class, numberFormat, false));
}

谢谢


问题答案:

也许error.code不能保证返回最特定的消息代码。尝试整体传递错误消息:

<spring:message message = "${error}" />