jsp EL表达式中令人郁闷的int/float/char
博客分类: java webjava开发常见问题分析
在EL表达式计算过程中,有朋友会遇到许多奇怪的问题,经常非常郁闷,在此我把这些总结一下,方便查询:
1、所有的整数数字字面量都是Long类型的;
2、所有小数字面量都是Double类型的;
3、""或''声明的是字符串,即''也是字符串,非char;
4、比较时都是equals比较。
接下来看几个可能出问题的例子,你会遇到一下的几个呢:
1、
如${1+2147483647} 结果是多少?
如果在java程序里边运行会得到-2147483648,而在jsp el中会得到2147483648。
2、
<%
Map
map.put(new Long(1), 123);
request.setAttribute("map", map);
request.setAttribute("a", new Long(1));
%>
${map[1]} 正确
${map[a]} 正确
3、
<%
Map
map.put(new Integer(1), 123);
request.setAttribute("map", map);
request.setAttribute("a", new Long(1));
request.setAttribute("b", new Integer(1));
%>
${map[1]} 错误
${map[a]} 错误
${map[b]} 正确
4、
<%
Map
map.put(1.1, 123); //map.put(1.1d, 123);
request.setAttribute("map", map);
request.setAttribute("a", new Double(1.1));
%>
map.a=${map[1.1]} 正确
map.a=${map[a]} 正确
5、
<%
Map
map.put(1.1f, 123); //map.put(new Float(1.1), 123);
request.setAttribute("map", map);
request.setAttribute("a", new Double(1.1));
request.setAttribute("b", new Float(1.1));
%>
map.a=${map[1.1]} 错误
map.a=${map[a]} 错误
map.a=${map[b]} 正确
6、
结合struts2的ognl表达式
${map['a']} ------------>错误, 因为'a'在jsp el表达式中是字符串,不能=char。
${map['a']}
补充:
在EL表达式规范2.2中,定义了:
写道
■ The value of an IntegerLiteral ranges from Long.MIN_VALUE to
Long.MAX_VALUE
■ The value of a FloatingPointLiteral ranges from Double.MIN_VALUE to
Double.MAX_VALUE
在tomcat7.0.6实现中,jasper.jar(实现了EL2.2规范):
AstFloatingPoint表示小数,AstInteger表示整数,其定义如下:
Java代码 public final class AstInteger extends SimpleNode
{
private volatile Number number;
public AstInteger(int id)
{
super(id);
}
protected Number getInteger()
{
if (this.number == null) {
try {
this.number = new Long(this.image);
} catch (ArithmeticException e1) {
this.number = new BigInteger(this.image);
}
}
return this.number;
}
public Class< > getType(eva luationContext ctx)
throws ELException
{
return getInteger().getClass();
}
public Object getValue(eva luationContext ctx)
throws ELException
{
return getInteger();
}
}
Java代码 public final class AstFloatingPoint extends SimpleNode
{
private volatile Number number;
public AstFloatingPoint(int id)
{
super(id);
}
public Number getFloatingPoint()
{
if (this.number == null) {
try {
this.number = new Double(this.image);
} catch (ArithmeticException e0) {
this.number = new BigDecimal(this.image);
}
}
return this.number;
}
public Object getValue(eva luationContext ctx)
throws ELException
{
return getFloatingPoint();
}
public Class< > getType(eva luationContext ctx)
throws ELException
{
return getFloatingPoint().getClass();
}
}
+ - * /实现,此处只看+的:
Java代码 package org.apache.el.parser;
import javax.el.ELException;
import org.apache.el.lang.ELArithmetic;
import org.apache.el.lang.eva luationContext;
public final class AstPlus extends ArithmeticNode
{
public AstPlus(int id)
{
super(id);
}
public Object getValue(ev