您的位置:首页 > 其它

EL表达式取出Map集合中key为Integer类型的值,bug解决方案

2017-03-16 21:38 441 查看


EL表达式取出Map集合中key为Integer类型的值,bug解决方案

    今天,我在用EL表达式取Map集合中key为Integer类型的值时,发现无法取出。

   问题 Demo如下:

<body>

<%

//创建Student对象

Student stu1 = new Student(1, "木丁西", '男', 24);

Student stu2 = new Student(2, "小龙女", '女', 14);

Student stu3 = new Student(3, "张馨予", '女', 28);

Student stu4 = new Student(4, "刘先生", '男', 35);

//创建Map集合对象

Map<Integer, Student> map = new HashMap();

//添加数据到 Map结合中

map.put(1, stu1);

map.put(2, stu2);

map.put(3, stu3);

map.put(4, stu4);

//保存集合对象到page域对象中。

pageContext.setAttribute("map", map);

%>


 <%-- 使用EL表达式获取Map集合对象 --%>

EL表达式获取集合对象:${map }<br/>

EL表达式获取集合中的第1个对象:${map[1]}<br/>

</body>


效果:



原因分析:
     从网上链接1:http://www.codeweblog.com/el%E8%A1%A8%E8%BE%BE%E5%BC%8Fmap-key%E4%B8%BAinteger%E7%B1%BB%E5%9E%8B-%E5%8F%96%E5%80%BCbug%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/ 链接2:http://stackoverflow.com/questions/924451/el-access-a-map-value-by-integer-key 获知。EL表达式在解析Integer类型数字的时候,会自动把数字转换成Long类型,后台使用Integer类型作为key值,进行判断的时候Integer与Long对象不相等。导致无法取出key值。

解决方案:使用Long类型作为Map中的键值类型。

Demo如下:

 <%@ page language="java" import="java.util.*, com.cn.entity.Student" pageEncoding="UTF-8"

session="true"

%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">


<title>My JSP 'el.jsp' starting page</title>


<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

	<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->


</head>


 <body>

<%

//创建Student对象

Student stu1 = new Student(1, "木丁西", '男', 24);

Student stu2 = new Student(2, "小龙女", '女', 14);

Student stu3 = new Student(3, "张馨予", '女', 28);

Student stu4 = new Student(4, "刘先生", '男', 35);

//创建Map集合对象

	Map<Long, Student> map = new HashMap();

//添加数据到 Map结合中

	map.put(1L, stu1);

	map.put(2L, stu2);

	map.put(3L, stu3);

	map.put(4L, stu4);

//保存集合对象到page域对象中。

pageContext.setAttribute("map", map);

%>


 <%-- 使用EL表达式获取Map集合对象 --%>

EL表达式获取集合对象:${map }<br/>

EL表达式获取集合中的第1个对象:${map[1]}<br/>

</body>

</html>


效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: