JavaWeb之EL表達式&JSTL標籤02

王振國老師整理

 

 

EL 表達式

什麼是 EL 表達式,EL 表達式的作用?

EL 表達式的全稱是:Expression Language。是表達式語言。

EL 表達式的什麼作用:EL 表達式主要是代替 jsp 頁面中的表達式腳本在 jsp 頁面中進行數據的輸出。 因爲 EL 表達式在輸出數據的時候,要比 jsp 的表達式腳本要簡潔很多。

EL 表達式的格式是:

  • ${表達式}

EL 表達式在輸出 null 值的時候,輸出的是空串。jsp 表達式腳本輸出 null 值的時候,輸出的是 null 字符串。

<body>
    <%
        request.setAttribute("key","值");
    %>
    表達式腳本輸出 key 的值是:
    <%=request.getAttribute("key1")==null?"":request.getAttribute("key1")%><br/>
    EL 表達式輸出 key 的值是:${key1}
</body>

EL 表達式搜索域數據的順序

EL 表達式主要是在 jsp 頁面中輸出數據。

主要是輸出域對象中的數據。

當四個域中都有相同的 key 的數據的時候,EL 表達式會按照四個域的從小到大的順序去進行搜索,找到就輸出。

EL 表達式輸出 Bean 的普通屬性,數組屬性。List 集 合屬性,map 集合屬性

需求——輸出 Person 類中普通屬性,數組屬性。list 集合屬性和 map 集合屬性。

Person 類

public class Person {
    // i.需求——輸出 Person 類中普通屬性,數組屬性。list 集合屬性和 map 集合屬性。
    private String name;
    private String[] phones;
    private List<String> cities;
    private Map<String,Object> map;
    public int getAge() {
        return 18;
}

輸出的代碼:

<body>
<%
    Person person = new Person();
    person.setName("國哥好帥!");
    person.setPhones(new String[]{"18610541354", "18688886666", "18699998888"});
    List<String> cities = new ArrayList<String>();
    cities.add("北京");
    cities.add("上海");
    cities.add("深圳");
    person.setCities(cities);
    Map<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");
    person.setMap(map);
    pageContext.setAttribute("p", person);
%>
    輸出 Person:${ p }<br/>
    輸出 Person 的 name 屬性:${p.name} <br>
    輸出 Person 的 pnones 數組屬性值:${p.phones[2]} <br>
    輸出 Person 的 cities 集合中的元素值:${p.cities} <br>
    輸出 Person 的 List 集合中個別元素值:${p.cities[2]} <br>
    輸出 Person 的 Map 集合: ${p.map} <br>
    輸出 Person 的 Map 集合中某個 key 的值: ${p.map.key3} <br>
    輸出 Person 的 age 屬性:${p.age} <br>
</body>

EL 表達式——運算

語法:${ 運算表達式 }

 EL 表達式支持如下運算符:

1)關係運算

2)邏輯運算

3)算數運算

empty 運算

  • empty 運算可以判斷一個數據是否爲空,如果爲空,則輸出 true,不爲空輸出 false。

以下幾種情況爲空:

  • 值爲 null 值的時候,爲空
  • 值爲空串的時候,爲空
  • 值是 Object 類型數組,長度爲零的時候
  • list 集合,元素個數爲零
  • map 集合,元素個數爲零
<body>
<%
    // 1、值爲 null 值的時候,爲空
    request.setAttribute("emptyNull", null);
// 2、值爲空串的時候,爲空
    request.setAttribute("emptyStr", "");
// 3、值是 Object 類型數組,長度爲零的時候
    request.setAttribute("emptyArr", new Object[]{});
// 4、list 集合,元素個數爲零
    List<String> list = new ArrayList<>();
// list.add("abc");
    request.setAttribute("emptyList", list);
// 5、map 集合,元素個數爲零
    Map<String,Object> map = new HashMap<String, Object>();
// map.put("key1", "value1");
    request.setAttribute("emptyMap", map);
%>
${ empty emptyNull } <br/>
${ empty emptyStr } <br/>
${ empty emptyArr } <br/>
${ empty emptyList } <br/>
${ empty emptyMap } <br/>
</body>

“.”點運算 和 [] 中括號運算符

.點運算,可以輸出 Bean 對象中某個屬性的值

[]中括號運算,可以輸出有序集合中某個元素的值。 並且[]中括號運算,還可以輸出 map 集合中 key 裏含有特殊字符的 key 的值。

<body>
<%
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("a.a.a", "aaaValue");
    map.put("b+b+b", "bbbValue");
    map.put("c-c-c", "cccValue");
    request.setAttribute("map", map);
%>
${ map['a.a.a'] } <br>
${ map["b+b+b"] } <br>
${ map['c-c-c'] } <br>
</body>

EL 表達式的 11 個隱含對象

EL 個達式中 11 個隱含對象,是 EL 表達式中自己定義的,可以直接使用。

變量                     類型                         作用
pageContext         PageContextImpl         它可以獲取 jsp 中的九大內置對象
pageScope           Map<String,Object>      它可以獲取 pageContext 域中的數據
requestScope        Map<String,Object>      它可以獲取 Request 域中的數據
sessionScope        Map<String,Object>      它可以獲取 Session 域中的數據
applicationScope    Map<String,Object>      它可以獲取 ServletContext 域中的數據
param               Map<String,String>      它可以獲取請求參數的值
paramValues         Map<String,String[]>    它也可以獲取請求參數的值,獲取多個值的時候使用。
header              Map<String,String>      它可以獲取請求頭的信息
headerValues        Map<String,String[]>    它可以獲取請求頭的信息,它可以獲取多個值的情況
cookie              Map<String,Cookie>      它可以獲取當前請求的 Cookie 信息
initParam           Map<String,String>      它可以獲取在 web.xml 中配置的<context-param>上下文參數

EL 獲取四個特定域中的屬性

pageScope         ======     pageContext 域
requestScope      ======     Request 域
sessionScope      ======     Session 域
applicationScope  ======     ServletContext 域

pageContext 對象的使用

  • 協議
  • 服務器 ip
  • 服務器端口
  • 獲取工程路徑
  • 獲取請求方法
  • 獲取客戶端 ip 地址
  • 獲取會話的 id 編號
<body>
<%--
request.getScheme() 它可以獲取請求的協議
request.getServerName() 獲取請求的服務器 ip 或域名
request.getServerPort() 獲取請求的服務器端口號
getContextPath() 獲取當前工程路徑
request.getMethod() 獲取請求的方式(GET 或 POST)
request.getRemoteHost() 獲取客戶端的 ip 地址
session.getId() 獲取會話的唯一標識
--%>
<%
    pageContext.setAttribute("req", request);
%>
<%=request.getScheme() %> <br>
1.協議: ${ req.scheme }<br>
2.服務器 ip:${ pageContext.request.serverName }<br>
3.服務器端口:${ pageContext.request.serverPort }<br>
4.獲取工程路徑:${ pageContext.request.contextPath }<br>
5.獲取請求方法:${ pageContext.request.method }<br>
6.獲取客戶端 ip 地址:${ pageContext.request.remoteHost }<br>
7.獲取會話的 id 編號:${ pageContext.session.id }<br>
</body>

EL 表達式其他隱含對象的使用

param         Map<String,String>     它可以獲取請求參數的值
paramValues   Map<String,String[]>   它也可以獲取請求參數的值,獲取多個值的時候使用。

 示例代碼:

輸出請求參數 username 的值:${ param.username } <br>
輸出請求參數 password 的值:${ param.password } <br>
輸出請求參數 username 的值:${ paramValues.username[0] } <br>
輸出請求參數 hobby 的值:${ paramValues.hobby[0] } <br>
輸出請求參數 hobby 的值:${ paramValues.hobby[1] } <br>

請求地址:

http://localhost:8080/09_EL_JSTL/other_el_obj.jsp?username=wzg168&password=666666&hobby=java&hobby=cpp

 

header         Map<String,String>   它可以獲取請求頭的信息

headerValues   Map<String,String[]> 它可以獲取請求頭的信息,它可以獲取多個值的情況

示例代碼:

輸出請求頭【User-Agent】的值:${ header['User-Agent'] } <br>
輸出請求頭【Connection】的值:${ header.Connection } <br>
輸出請求頭【User-Agent】的值:${ headerValues['User-Agent'][0] } <br>

 

cookie Map<String,Cookie> 它可以獲取當前請求的 Cookie 信息

示例代碼:

獲取 Cookie 的名稱:${ cookie.JSESSIONID.name } <br>
獲取 Cookie 的值:${ cookie.JSESSIONID.value } <br>

 

initParam Map<String,String> 它可以獲取在 web.xml 中配置的<context-param>上下文參數

 示例代碼:

輸出&lt;Context-param&gt;username 的值:${ initParam.username } <br>
輸出&lt;Context-param&gt;url 的值:${ initParam.url } <br>

 

JSTL 標籤庫

JSTL 標籤庫 全稱是指 JSP Standard Tag Library JSP 標準標籤庫。是一個不斷完善的開放源代碼的 JSP 標 籤庫。

EL 表達式主要是爲了替換 jsp 中的表達式腳本,而標籤庫則是爲了替換代碼腳本。這樣使得整個 jsp 頁面 變得更佳簡潔。

JSTL 由五個不同功能的標籤庫組成。

在 jsp 標籤庫中使用 taglib 指令引入標籤庫

CORE 標籤庫
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
XML 標籤庫
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
FMT 標籤庫
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
SQL 標籤庫
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
FUNCTIONS 標籤庫
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

JSTL 標籤庫的使用步驟

先導入 jstl 標籤庫的 jar 包。

  • taglibs-standard-impl-1.2.1.jar
  • taglibs-standard-spec-1.2.1.jar

第二步,使用 taglib 指令引入標籤庫

  • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 

core 核心庫使用

<c:set />(使用很少)

作用:set 標籤可以往域中保存數據

<%--
i.<c:set />
作用:set 標籤可以往域中保存數據
域對象.setAttribute(key,value);
scope 屬性設置保存到哪個域
page 表示 PageContext 域(默認值)
request 表示 Request 域
session 表示 Session 域
application 表示 ServletContext 域
var 屬性設置 key 是多少
value 屬性設置值
--%>
保存之前:${ sessionScope.abc } <br>
<c:set scope="session" var="abc" value="abcValue"/>
保存之後:${ sessionScope.abc } <br>

<c:if />

  • if 標籤用來做 if 判斷。
<%--
ii.<c:if />
if 標籤用來做 if 判斷。
test 屬性表示判斷的條件(使用 EL 表達式輸出)
--%>
<c:if test="${ 12 == 12 }">
<h1>12 等於 12</h1>
</c:if>
<c:if test="${ 12 != 12 }">
<h1>12 不等於 12</h1>
</c:if>

<c:choose> <c:when> <c:otherwise>標籤

作用:多路判斷。跟 switch ... case .... default 非常接近

<%--
iii.<c:choose> <c:when> <c:otherwise>標籤
作用:多路判斷。跟 switch ... case .... default 非常接近
choose 標籤開始選擇判斷
when 標籤表示每一種判斷情況
test 屬性表示當前這種判斷情況的值
otherwise 標籤表示剩下的情況
<c:choose> <c:when> <c:otherwise>標籤使用時需要注意的點:
1、標籤裏不能使用 html 註釋,要使用 jsp 註釋
2、when 標籤的父標籤一定要是 choose 標籤
--%>
<%
request.setAttribute("height", 180);
%>
<c:choose>
<%-- 這是 html 註釋 --%>
<c:when test="${ requestScope.height > 190 }">
<h2>小巨人</h2>
</c:when>
<c:when test="${ requestScope.height > 180 }">
<h2>很高</h2>
</c:when>
<c:when test="${ requestScope.height > 170 }">
<h2>還可以</h2>
</c:when>
<c:otherwise>
<c:choose>
<c:when test="${requestScope.height > 160}">
<h3>大於 160</h3>
</c:when>
<c:when test="${requestScope.height > 150}">
<h3>大於 150</h3>
</c:when>
<c:when test="${requestScope.height > 140}">
<h3>大於 140</h3>
</c:when>
<c:otherwise>
其他小於 140
</c:otherwise>
</c:choose>
</c:otherwise>
</c:choose>

<c:forEach />

作用:遍歷輸出使用。

  • 遍歷 1 到 10,輸出

示例代碼:

<%--1.遍歷 1 到 10,輸出
begin 屬性設置開始的索引
end 屬性設置結束的索引
var 屬性表示循環的變量(也是當前正在遍歷到的數據)
for (int i = 1; i < 10; i++)
--%>
<table border="1">
<c:forEach begin="1" end="10" var="i">
<tr>
<td>第${i}行</td>
</tr>
</c:forEach>
</table>
  • 遍歷 Object 數組

示例代碼:

<%-- 2.遍歷 Object 數組
for (Object item: arr)
items 表示遍歷的數據源(遍歷的集合)
var 表示當前遍歷到的數據
--%>
<%
request.setAttribute("arr", new String[]{"18610541354","18688886666","18699998888"});
%>
<c:forEach items="${ requestScope.arr }" var="item">
${ item } <br>
</c:forEach>
  • 遍歷 Map 集合

示例代碼:

<%
Map<String,Object> map = new HashMap<String, Object>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
// for ( Map.Entry<String,Object> entry : map.entrySet()) {
// }
request.setAttribute("map", map);
%>
<c:forEach items="${ requestScope.map }" var="entry">
<h1>${entry.key} = ${entry.value}</h1>
</c:forEach>
  • 遍歷 List 集合---list 中存放 Student 類,有屬性:編號,用戶名,密碼,年齡, 電話信息

Student 類:

public class Student {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String phone;

    public Integer getId() {
        return id;
    }

    public void setId( Integer id ) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername( String username ) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword( String password ) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge( Integer age ) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone( String phone ) {
        this.phone = phone;
    }
}

示例代碼:

<%--4.遍歷 List 集合---list 中存放 Student 類,有屬性:編號,用戶名,密碼,年齡,電話信息--%>
<%
List<Student> studentList = new ArrayList<Student>();
for (int i = 1; i <= 10; i++) {
studentList.add(new Student(i,"username"+i ,"pass"+i,18+i,"phone"+i));
}
request.setAttribute("stus", studentList);
%>
<table>
<tr>
<th>編號</th>
<th>用戶名</th>
<th>密碼</th>
<th>年齡</th>
<th>電話</th>
<th>操作</th>
</tr>
<%--
items 表示遍歷的集合
var 表示遍歷到的數據
begin 表示遍歷的開始索引值
end 表示結束的索引值
step 屬性表示遍歷的步長值
varStatus 屬性表示當前遍歷到的數據的狀態
for(int i = 1; i < 10; i+=2)
--%>
<c:forEach begin="2" end="7" step="2" varStatus="status" items="${requestScope.stus}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.username}</td>
<td>${stu.password}</td>
<td>${stu.age}</td>
<td>${stu.phone}</td>
<td>${status.step}</td>
</tr>
</c:forEach>
</table>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章