码迷,mamicode.com
首页 > 其他好文 > 详细

EL中拼接字符串的方法

时间:2014-09-25 18:50:27      阅读:447      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   java   ar   strong   

近期在项目中碰到一个需要在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>

String Concatenation Operator

To evaluate

A += B 
  • Coerce A and B to String.
  • Return the concatenated string of A and B.

EL中拼接字符串的方法

标签:style   blog   http   color   io   使用   java   ar   strong   

原文地址:http://www.cnblogs.com/weenix/p/3993233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!