JavaEE在線就業班2.0

  • 使用EL表達式獲取數據的語法:${標識符}download:JavaEE在線就業班2.0
  • EL表達式語句在執行時,會調用pageContext.findAttribute方法,用標識符爲關鍵字,分別從page、request、session、Application四個域中查找相應的對象,找到則返回相應的對象,找不到則返回「」(不是null)。
  • EL表達式能夠很輕鬆獲取javaBean的屬性,或獲取數組、Collection、Map類型集合的數據,例如:

    ${user.address.city}
    ${user.list[0]}:訪問有序集合某個位置的元素
    ${map.key}:得到map集合中指定key的值
  • 結合JSTL的foreach標籤,使用EL表達式也能夠很輕鬆迭代各類類型的數組或集合,如:迭代數組、迭代collection類型集合、迭代map類型集合。
    相關代碼:(工程el_example
    1.jsp

<%@page import="cn.itcast.Person"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>
  <head>
    <title>EL表達式獲取數據</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">

  </head>
  
  <body>
    <%
        request.setAttribute("name", "aaa");
     %>
     ${name }<%--翻譯成pageContext.findAttribute("name"); --%>     <br>
     <!-- 在JSP頁面中,使用EL表達式得到bean的屬性 -->
     <%
        Person person = new Person();
        person.setAge(12);
        request.setAttribute("person", person);
      %>
      ${person.age }      <br>
      <!-- 獲取list集合中指定位置的數據 -->
      <%
        Person p1 = new Person();
        p1.setName("aaa");
        
        Person p2 = new Person();
        p1.setName("bbb");
        
        List list = new ArrayList();
        list.add(p1);
        list.add(p2);
        request.setAttribute("list", list);
       %>
       ${list[1].name}       
       <!-- 迭代集合 -->
       <c:forEach var="person" items="${list }">
            ${person.name}       </c:forEach>
       <br>
       <!-- 在jsp頁面中,使用EL表達式獲取map集合的數據 -->
       <%
            Map map = new HashMap();
            map.put("a", "aaa");
            map.put("b", "bbb");
            map.put("c", "ccc");
            map.put("1", "111");
            request.setAttribute("map", map);
        %>
        ${map.c }<!-- 根據關鍵字取map集合的數據 --><br>
        
        ${map["1"]}<br>
        <c:forEach var="me" items="${map}">
            ${me.key} = ${me.value }        </c:forEach>
        
  </body></html>

注意:使用EL表達式表達式取得數據時通常都用「.」運算符,若是取不出來再使用「[]」運算符,好比Map的關鍵字是數字則須要使用[]。php

相關文章
相關標籤/搜索