Spring使用typeMismatch消息

boy*_*715 8 data-binding spring-mvc

我在网上和stackoverflow中做了一些搜索,看看如何处理我在其中一个屏幕上看到的以下消息:

无法将类型[java.lang.String]的属性值转换为属性'qtyToShip'的必需类型[java.lang.Long]; 嵌套异常是java.lang.IllegalArgumentException:无法解析数字:Unparseable number:"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
Run Code Online (Sandbox Code Playgroud)

我在消息中添加整数值以确定哪一个会显示.

现在在我的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>
Run Code Online (Sandbox Code Playgroud)

以上是在我的表格之外,在我的表格中我有以下(测试理想)

所以结果是当我运行我的代码来触发错误时,我看到在我的表单中我收到以下消息:

1. Invalid value for Qty To Ship, accepts only numbers.
Run Code Online (Sandbox Code Playgroud)

其中包括:typeMismatch.shippingCommand.qtyToShip

表单外部显示:

Invalid type entered
Run Code Online (Sandbox Code Playgroud)

我不明白的是为什么我能在表格中显示正确的信息但不在外面?

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

@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));
}
Run Code Online (Sandbox Code Playgroud)

谢谢

axt*_*avt 6

也许error.code并不保证返回最具体的消息代码.尝试将错误消息作为一个整体传递:

<spring:message message = "${error}" />   
Run Code Online (Sandbox Code Playgroud)

  • 枪的儿子 - 这就是诀窍.谢谢 (2认同)