更新时间:2023-02-26 13:09:46
您可以尝试使用c:catch
将字符串隐式转换为数字并捕获任何异常(如果有).例如:
You could try to implicitly cast a string to a number and catch any exception (if there is one) using c:catch
. For example:
<c:catch var="catchString">
<c:set var="myString" value="${0 + 'asd1234'}" />
</c:catch>
<c:if test="${not empty catchString}">
<p>Failed: ${catchString}</p>
</c:if>
<c:catch var="catchNumber">
<c:set var="myNumber" value="${0 + '1234'}" />
</c:catch>
<c:if test="${not empty catchNumber}">
<p>Failed: ${catchNumber}</p>
</c:if>
将输出以下内容:
<p>Failed: java.lang.NumberFormatException: For input string: "asd1234"</p>
如果要防止浮点,可以使用fmt:formatNumber
进行检查以检查小数点:
If you want to prevent floats you could build a check using fmt:formatNumber
to check for decimals:
<c:set var="myFloat" value="12"/>
<fmt:formatNumber value="${myFloat}" pattern="0" var="myInteger"/>
<c:if test="${myInteger - myFloat eq 0}">
<p>No decimals</p>
</c:if>
当然,您可以将其与c:catch
结合使用以捕获数字格式异常.
Of course you could combine this with the c:catch
to catch number format exceptions.
<c:set var="myString" value="abc12.34"/>
<c:catch>
<fmt:formatNumber value="${myString}" pattern="0" var="myInteger"/>
<c:set var="passed" value="${myInteger - myString eq 0}"/>
</c:catch>
<c:if test="${passed}">
<p>Passed</p>
</c:if>
<c:if test="${not passed}">
<p>Failed</p>
</c:if>