近期在項目中碰到一個需要在JSP頁面中比較兩String類型的值的問題,於是想當然的寫了如下代碼:
<c:if test="${'p'+longValue=='p1'}">some text</c:if>
其中longValue是requestScope中一個Long類型的值,訪問JSP頁面,報錯,查看控制台,拋了NumberFormatException異常
java.lang.NumberFormatException: For input string: "p"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:410)
at java.lang.Long.valueOf(Long.java:525)
...
由出錯信息可得知EL嘗試將字符"p"解析為Long類型的值然后進行算術運算,查詢文檔,有下面一段話:
All of the binary arithmetic operations prefer Double values and all of them will resolve to 0 if either of their operands is null. The operators + - * % will try to coerce their operands to Long values if they cannot be coerced to Double.
由此可以知道+操作符在EL中只是一個算術運算符,不能用來進行字符串拼接。只能使用其他辦法。
由於EL中能直接調用對象的方法,而String類型對象中有一個concat(String str) 方法,返回值為拼接str之后的結果字符串。
而且基本類型能自動轉為String類型作為concat的傳入參數,於是修改代碼為:
<c:if test="${'p'.concat(longValue)=='p1'}">some text</c:if>
運行結果一切正常。
后查閱 EL 3.0 Specification 文檔,看到EL3.0提供了字符串拼接運算符"+="。
String Concatenation Operator
To evaluate
A += B
- Coerce A and B to String.
- Return the concatenated string of A and B.
於是在EL3.0中可以使用以下代碼:
<c:if test="${('p'+=longValue)=='p1'}">some text</c:if>