1. 程式人生 > >EL表示式及其定義和使用

EL表示式及其定義和使用

簡介

EL(Expression Language)表示式語言實在JSP2.0版本中引入的新特性,它用於JSP檔案中的資料訪問。這種表示式語言能簡化JSP檔案中資料訪問的程式碼,可用來代替傳統的基於”<%=”和”%>”形式的Java表示式,以及部分基於“<%”heels“%>”形式的Java程式片段。

例如:

<%

         ShoppingCart cart =(ShoppingCart)session.getAttribute(“cart”);

if(cart != null){

%>

<%=cart.getTotal()%>

<%} %>

上述程式碼等價於:

${sessionScope.cart.total}

基本語法

EL表示式的基本形勢為:${var},所有的表示式都以”${”符號開頭,以”}”符號結尾。如果在JSP檔案的模版檔案中使用EL表示式,那麼表示式的值會輸出到網頁上。

例如以下Java表示式和El表示式的作用相同,都用於輸出請求引數username:

Java表示式:<%=request.getParameter(“username”)%>

EL表示式:${param.username}

比較以上兩種表示式的形式,可以看出,EL表示式使得JSP檔案的穿件人員能用更加簡單的語法來訪問資料。

EL表示式和Java表示式一樣,既可以直接插入到JSP檔案的模版檔案中,也可以作為JSP標籤的屬性的值:

<jsp:useBeanid=”myBean” scope=”page” class=”defaultPackage.CounterBean”/>

<jsp:setProerptyname=”myBean” property=”count” value=”${myBean.count+1}”/>

Current countvalue is :${myBean.count}

訪問物件的屬性及陣列的元素

EL表示式語言可以使用點號運算子”.”來訪問物件的屬性,例如表示式${customer.name}表示customer物件的name屬性。

EL表示式語言也可以使用方括號運算子”[]”來訪問物件的屬性,例如表示式${customer[“name”]}和${customer.name}是等價的。

方括號運算子”[]”還可以用來訪問陣列中的元素,例如${sustomers[0]}表示訪問customers陣列中的第一個元素。

EL語言的運算子

運算子型別

運算子

說明

範例

結果

+

${16+5}

21

-

${16-5}

11

*

${16*5}

80

/或div

${16/5}

3.2

%或mod

模(求餘)

${16%5}

1

==或eq

等於

${16==5}

false

!=或ne

不等於

${16!=5}

true

<或lt

小於

${16<5}

false

>或gt

大於

${16>5}

true

<=或le

小於等於

${16<=5}

false

>=或ge

大於等於

${16>=5}

true

邏輯

運算

&&或and

邏輯與

${16>5&&16<18}

true

||或or

邏輯或

${16>5||16<18}

true

!或not

邏輯非

${!(16>5)}

false

empty運算子

empty

檢查是否為空值

${empty var}

如果變數var為null,就返回true

條件運算子

a?b:c

條件運算子

${16>5?16:5}

16

EL語言提供了一個用於測試物件是否為空的特殊運算子“empty“,其語法形式為${empty var},它能判斷var變數(確切地說,應該是命名變數)是否為空。在以下情況下empty運算子返回true:

·  var變數不存在,即沒有定義。

·  var變數的值為null。

·  var變數引用集合(Set、List和Map)型別的物件,並且在i集合物件中不包含任何元素。

empty運算子可以與”!”運算子一起使用。

隱含物件

EL語言定義了11個隱含物件,他們都是java.util.Map型別。

EL表示式語言中的隱含物件

隱含物件的固定變數名

型別

說明

applicationScope

java.util.Map

把Web應用範圍內的屬性名和屬性值進行對映

cookie

java.util.Map

把客戶請求中的Cookie名和Cookie物件進行對映

header

java.util.Map

把HTTP請求頭部的專案名和專案值進行對映

headerValues

java.util.Map

把HTTP請求頭部的專案名和專案值的陣列進行對映,例如${headerValues[“accept-language”]}等價於<%=request.getHeaders(“accept-laguage”)%>

initParam

java.util.Map

把Web應用的初始化引數名和引數值進行對映

pageContext

java.util.Map

表示javax.servlet.jsp.PageContext物件

pageScope

java.util.Map

把頁面範圍內的屬性名和屬性值進行對映

param

java.util.Map

把客戶請求中的請求引數名和引數值進行對映

paramValues

java.util.Map

把客戶請求中的請求引數名和所有匹配的引數值陣列進行對映

resquestScope

java.util.Map

把請求範圍內的屬性名和屬性值進行對映

sessionScope

java.util.Map

把會話範圍內的屬性名和屬性值進行對映

命名變數

EL表示式中的變數稱為命名變數,它不是JSP檔案中的區域性變數或例項變數,而是存放在特定該範圍內的屬性,命名變數的名字和屬性名字對應。例如${username}等價於以下程式碼:

<%

Stringusername=(String)pageContext.finAttribute(“username”);

if(username != null){

%>

<%=username%>

<%} %>

假如在Person類中並不存在username屬性,而是提供了public型別的getUsername()方法:

public String getUsername(){

returnthis.lastName + “.” + this.firstName;

}

就可以通過${person.username}表示式獲得person.getUsername()方法的返回值。

自定義和使用EL函式

EL表示式語言可以訪問EL函式。EL函式實際上與Java類的方法對應,這個Java類必須定義為public型別,並且作為函式的方法必須宣告為public static型別。當Java類定義好以後,應該在標籤描述符(TLD)檔案中,把Java類的方法對映為函式。

建立一個簡單的工具類,定義靜態方法localNowDate()方法,在頁面中顯示當前的本地時間。靜態方法styleTable1()設定常用的表格樣式,靜態方法funcAlert()自定義簡單的js方法,靜態方法返回一個自定義的頁面控制元件。

	public static String localNowDate(){
		Date date = new Date();
		String dateString = (1900+date.getYear()) + " 年 " + (date.getMonth() + 1) + " 月 " + date.getDate() + " 日    \n"
				+date.toLocaleString().substring(9);
		return dateString;
	}
	
	public static String styleTable1(){
		return "font-size:20px;color:#E91E63;background-color: #795548;";
	}
	
	public static String funcAlert(String content){
		System.out.println(content);
		return "alert('" + content +"')";
	}
	
	public static String myTable(){
		return "<table id='myTable' style='border-width:2px;border-style: solid;border-color:#795548;'>"
				+ "<tr style='background-color:#666666;'><th>Head1</th><th>Head2</th></tr>"
				+ "<tr><td>Element1</td><td>Element2</td></tr></table>";
	}
然後定義TLD檔案:
<?xml version="1.0" encoding="utf-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
	version="2.0">
	<tlib-version>1.0</tlib-version>
	<short-name>elDemo</short-name>
	<uri>elDemo</uri>
	<function>
		<description>show local now dateTime</description>
		<name>localNowDate</name>
		<function-class>dis.geo.demos.el.ELDemo</function-class>
		<function-signature>java.lang.String localNowDate()</function-signature>
	</function>
	
	<function>
		<description>styleTable1</description>
		<name>styleTable1</name>
		<function-class>dis.geo.demos.el.ELDemo</function-class>
		<function-signature>java.lang.String styleTable1()</function-signature>
	</function>
	
	<function>
		<description>styleTable1</description>
		<name>funcAlert</name>
		<function-class>dis.geo.demos.el.ELDemo</function-class>
		<function-signature>java.lang.String funcAlert(java.lang.String)</function-signature>
	</function>
	
	<function>
		<description>myTable</description>
		<name>myTable</name>
		<function-class>dis.geo.demos.el.ELDemo</function-class>
		<function-signature>java.lang.String myTable()</function-signature>
	</function>
</taglib>
在web.xml檔案中註冊taglib:
  <taglib>
  	<taglib-uri>/elDemo</taglib-uri>
  	<taglib-location>fiels/elDemo.tld</taglib-location>
  </taglib>
在JSP檔案中使用自定義的EL表示式:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" isELIgnored="false"%>
    <%@ taglib prefix="me" uri="/elDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>MyELDemo</title>
</head>
<script type="text/javascript">
	
</script>
<body>
	<p>${me:localNowDate()}</p><br/>
	<table style="${me:styleTable1()}">
		<tr>
			<td>1.1</td>
			<td>1.2</td>
			<td>1.3</td>
		</tr>
		<tr>
			<td>2.1</td>
			<td>2.2</td>
			<td>2.3</td>
		</tr>
		<tr>
			<td>3.1</td>
			<td>3.2</td>
			<td>3.3</td>
		</tr>
	</table>
	<hr/>
	<a href="#" onclick="${me:funcAlert('Clicked me!!!')}">click me</a>
	<hr/>
	${me:myTable() }
</body>
</html>

啟動伺服器,檢視頁面效果:


總結:

EL表示式的使用能夠簡化頁面內容,提高程式碼的複用率,其可以完成類似於自定義JSP標籤,CSS樣式。假如有這樣的一種情況,需要在頁面中使用內聯樣式,而樣式的內容又很多,這樣頁面中不僅有標籤還有大量的內聯樣式,不免有些混亂,使用上面例子中的自定義EL就可以解決此類問題。

EL=Expression  Language=Easy Language(簡化語言)