当值小于 10 时,在 jstl 标记中附加前导零
Append leading zeros in jstl tag when the value is less than 10
我的 jsp 视图中有一个 select 元素。我希望当值小于 10 时,它会在数字前附加 0
,因此 1
将是 01
。到目前为止,这是我的代码:
<select id="sample" name="sample">
<c:forEach var="i" begin="1" end="10">
<option value=${i}>${ i<12 ? "0"+i : i} hour</option>
</c:forEach>
</select>
当我 运行 我的代码出现错误 java.lang.NumberFormatException: For input string:
。我的代码有什么问题?
在 EL 中,+
是加法运算符,不是字符串连接运算符。字符串连接运算符仅在 EL 3.0 版后可用,如 +=
.
不过,这里不需要。只需内联两个表达式,如下所示:
<option value="${i}">${i < 10 ? '0' : ''}${i} hour</option>
请注意,我还修复了逻辑错误。
您还可以使用 fmt
标签库:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<option value="${i}"><fmt:formatNumber type="number" minIntegerDigits="2" value="${i}" /> hour</option>
我的 jsp 视图中有一个 select 元素。我希望当值小于 10 时,它会在数字前附加 0
,因此 1
将是 01
。到目前为止,这是我的代码:
<select id="sample" name="sample">
<c:forEach var="i" begin="1" end="10">
<option value=${i}>${ i<12 ? "0"+i : i} hour</option>
</c:forEach>
</select>
当我 运行 我的代码出现错误 java.lang.NumberFormatException: For input string:
。我的代码有什么问题?
在 EL 中,+
是加法运算符,不是字符串连接运算符。字符串连接运算符仅在 EL 3.0 版后可用,如 +=
.
不过,这里不需要。只需内联两个表达式,如下所示:
<option value="${i}">${i < 10 ? '0' : ''}${i} hour</option>
请注意,我还修复了逻辑错误。
您还可以使用 fmt
标签库:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<option value="${i}"><fmt:formatNumber type="number" minIntegerDigits="2" value="${i}" /> hour</option>