zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用EL表达式访问集合

集合 访问 表达式 el 使用
2023-09-14 09:04:54 时间

在 EL 表达式中,同样可以获取集合的数据,这些集合可能是 Vector、List、Map、数组等。可以在 JSP 中获取这些对象,继而显示其中的内容,其语法格式如下: 

  1. ${collection [序号]}

其中,collection 代表集合对象的名称。例如:

  1. ${books [0]}

表示集合 books 中下标为 0 的元素。

上面表示的是一维集合,如数组、List 等,若操作的集合为二维集合,如 HashMap,其值是 key 和 value 值对的形式,则值 (value) 可以这样显示:

  1. ${collection.key}

例如:

  1. ${p1.ID}

表示显示名为 pi 的 HashMap 中的 key 为 ID 的元素的值。下面是通过 EL 表达式访问集合的一个案例。

【例1】通过 EL 表达式访问集合(collection_demo.jsp):

  1. <%@ page language="java" contentType="text/html;charset=utf-8" %>
  2. <%@ page import="java.util.*" %>
  3. <html>
  4. <head>
  5. <title>使用 EL 访问集合</title>
  6. </head>
  7. <body>
  8. <h1>使用 EL 访问集合</ h1>
  9. <hr/>
  10. <%
  11. List books=new ArrayList();
  12. books.add("Java语言程序设计");
  13. books.add("高等数学");
  14. session.setAttribute("books",books);
  15. HashMap stu=new HashMap();
  16. stu.put("stuno","00002");
  17. stu.put("stuname","夜华");
  18. session.setAttribute("stu",stu);
  19. %>
  20. <h3>books 中的内容是:${books[0]},${books[1]}</h3>
  21. <h3>stu 中的内容是:${stu.stuno},${stu.stuname}</h3>
  22. </body>
  23. </html>

程序运行结果如图 1 所示。


图1 使用EL访问集合