程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> JSTL和EL介紹

JSTL和EL介紹

編輯:關於JSP

JSTL規范介紹
------------------------------------------------
JSTL:
* JSTL即JSP Standard Tag Library的縮寫
* 一些常用的JSP標簽
* 和MVC框架結合使用很方便,如果struts、spring mvc
* 不是JSP 1.2,2.0,2.1規范的一部分,需要單獨下載。下表是servlet、jsp、jstl、j2ee規范的對應關系:
Servlet Version          JSP Version            JSTL  Version          Java EE Version
2.5                               2.1                             1.2                             5
2.4                               2.0                             1.1                            1.4
2.3                               1.2                             1.0                            1.2

EL:
* EL即JSP Expression Language(JSP表達式語言)
* EL來源於JSTL,jsp 2.0、2.1中已實現了EL規范

注:本文是按照jstl1.2的規范來介紹的,sql和xml標簽未做介紹!

Core Tags(核心標簽)
------------------------------------------------
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:out>
語法:
<c:out value=”value” [escapeXml=”{true|false}”] [default=”defaultValue”] />

描述:
輸出一個表達式的值,和 <%= ... > scriptlet類似,但在c:out中可以用'.'訪問對象屬性值。

例子:
<c:out value="${'<tag> , &'}"/>  >>>>>  <tag> , &
<c:out value="${customer.address.street}"/>==${customer.address.street}(JSP2.0/2.1)  >>>>>  street的值
EL表達式的取值默認順序:pageScope  requestScope  sessionScope  applicationScope
<c:out value="${requestScope.foo}"/>
<c:out value="${requestScope['foo']}"/>
<c:out value="${param['foo']}"/>
<c:out value="${param['foo']}"/>
<c:out value="${paramValues['foo']}"/>


<c:set>
語法:
<c:set value=”value” var=”varName” [scope=”{ page|request|session|application}”]/>
<c:set value=”value” target=”target” property=”propertyName”/>

描述:
將表達式計算出來的值賦值給某一變量或map中的對象

例子:
<c:set var="foo" value="${foo2 * 2}" scope="page"/>  scope="{page|request|session|application}"
<c:set target="${cust.address}" property="city" value="wuhan..."/>
<c:set target="${myMap}" property="color" value="red"/>

<c:remove>
語法:
<c:remove var=”varName” [scope=”{page|request|session|application}”]/>

描述:
從不同的scope中刪除某變量,沒有指定scope,則從PageContext中刪除對象

例子:
<c:remove var=”myVar”/>

<c:catch>
語法:
<c:catch [var=”varName”]>
nested actions
</c:catch>

描述:
捕獲標簽內部的java.lang.Throwable

例子:
<c:catch var ="catchException">
   <% int x = 5/0;%>
</c:catch>
<c:if test = "${catchException != null}">
   <p>The exception is : ${catchException} <br />
   There is an exception: ${catchException.message}</p>
</c:if>

<c:if>
語法:
<c:if test=”testCondition ” [var=”varName”] [scope=”{page|request|session|application}”]>
body content
</c:if>

描述:
如果表達式判斷為true,則會執行標簽體內的內容

例子:
<c:set var="salary" scope="session" value="${2000*2}"/>
<c:if test="${salary > 2000}">
   <p>My salary is: <c:out value="${salary}"/><p>
</c:if>

<c:choose>,<c:when>,<c:otherwise>
和switch類似
<c:choose>
    <c:when test="${salary <= 0}">
       Salary is very low to survive.
    </c:when>
    <c:when test="${salary > 1000}">
        Salary is very good.
    </c:when>
    <c:otherwise>
        No comment sir...
    </c:otherwise>
</c:choose>

<c:import>,<c:param>
語法:
<c:import url=”url” [context=”context”] [var=”varName”] [scope=”{page|request|session|application}”] [charEncoding=”charEncoding”]>
optional body content for <c:param name=”name” value=”value”/> subtags
</c:import>

描述:
<c:import>和<jsp:include>動作類似,但是c:import可以從其他的站點或FTP獲取資源

例子:
<c:import var="data" url="http://www.tutorialspoint.com"/>
<c:out value="${data}"/>

<c:forEach>
語法:
<c:forEach [var=”varName”] items=”collection” [varStatus=”varStatusName ”] [begin=” begin”] [end=”end ”] [step=”step”]>
body content
</c:forEach>
<c:forEach [var=”varName”] [varStatus=”varStatusName ”] begin=”begin” end=”end” [step=”step”]>
body content
</c:forEach>

描述:
根據給定的集合變量,循環輸出標簽體的信息。或者將標簽體的信息循環指定次數。
status變量包含屬性
current:當前這次迭代的(集合中的)項
index:當前這次迭代從 0 開始的迭代索引
count:當前這次迭代從 1 開始的迭代計數
first:用來表明當前這輪迭代是否為第一次迭代的標志
last:用來表明當前這輪迭代是否為最後一次迭代的標志
begin:begin屬性值
end:end屬性值
step:step屬性值

例子:
<c:forEach var="i" begin="1" end="5">
   Item <c:out value="${i}"/>
</c:forEach>

<c:forEach var="m" items="${myMap}" begin="1" end="5" varStatus="stat">
   Item <c:out value="${m.color}"/>
   <c:if test="${stat.last}">
   last....
   </c:if>
</c:forEach>
 
<c:forTokens>
語法:
<c:forTokens items="stringOfTokens" delims="delimiters" [var="varName"] [varStatus="varStatusName "] [begin=" begin"] [end="end "] [step="step"]>
body content
</c:forTokens>

描述:
遍歷有分隔符號的字符串

例子:
<c:forTokens items="Zara,nuha,roshy" delims="," var="name">
   <c:out value="${name}"/>
</c:forTokens>

<c:redirect>
語法:
<c:redirect url=”value” [context=”context”]/>
<c:redirect url=”value” [context=”context”]>
<c:param name=".." value=".."/>
</c:redirect>

描述:
和HttpServletResponse.sendRedirect()類似

例子:
<c:redirect url="http://www.photofuntoos.com">
    <c:param name="a" value="hello"/>
</c:redirect>

<c:url>
語法
<c:url value=”value” [context=”context”] [var=”varName”] [scope=”{page|request|session|application}”]/>
<c:url value=”value” [context=”context”] [var=”varName”] [scope=”{page|request|session|application}”]>
<c:param name=".." value=".." />
</c:url>

描述:
構建一個URL

例子:
<a href="<c:url value="/jsp/index.htm"/>">TEST</a>

Formatting tags(格式化標簽)
------------------------------------------------
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 
<fmt:formatNumber>
語法:
<fmt:formatNumber value=”numericValue” [type=”{ number|currency|percent}”] [pattern=”customPattern ”] [currencyCode=”currencyCode”] [currencySymbol=”currencySymbol”]
    [groupingUsed=”{true|false}”] [maxIntegerDigits= ”maxIntegerDigits” ] [minIntegerDigits= ”minIntegerDigits” ] [maxFractionDigits=”maxFractionDigits”]
    [minFractionDigits=”minFractionDigits”] [var=”varName”] [scope=”{page|request|session|application}”]/>

描述:
格式化數字

例子:
<c:set var="balance" value="120000.2309" />
<fmt:formatNumber value="${balance}" type="currency"/>  ---->>> ¥120,000.23
<fmt:formatNumber type="number" value="${balance}" />   ---->>> 120,000.231
<fmt:formatNumber type="percent" value="${balance}" />  ---->>> 12,000,023%
<fmt:setLocale value="en_US"/>                         
<fmt:formatNumber value="${balance}" type="currency"/>  ---->>> $120,000.23

<fmt:parseNumber>
語法:
<fmt:parseNumber value= ”numericValue” [type=”{ number|currency|percent}”] [pattern=”customPattern ”] [parseLocale=”parseLocale”]
    [integerOnly=”{true|false}”]
    [var=”varName”]
    [scope=”{page|request|session|application}”]/>

描述:
字符串解析成數字、貨幣、百分數

例子:
<fmt:parseNumber value="1234567890" type="number"/>      ----->>> 1234567890
<fmt:parseNumber  value="78761234.3%" type="percent"/>   ----->>> 787612.343
<fmt:parseNumber  type="number" value="56a" />           ----->>> 56

<fmt:formatDate>
語法:
<fmt:formatDate value="date" [type="{time| date|both}"] [dateStyle="{ default|short|medium|long|full}"]
   [timeStyle="{ default|short|medium|long|full}"] [pattern="customPattern "] [timeZone="timeZone"] [var="varName"]
   [scope="{page|request|session|application}"]/>

描述:
按照設置的格式,格式化日期和/或時間

例子:
<c:set var="now" value="<%=new java.util.Date()%>" />
<fmt:formatDate type="time" value="${now}" />                ----->>> 11:50:10
<fmt:formatDate type="date" value="${now}" />                ----->>> 2012-8-21
<fmt:formatDate type="both" value="${now}" />                ----->>> 2012-8-21 11:50:10
<fmt:formatDate type="both" dateStyle="short" timeStyle="short" value="${now}" />     ----->>> 12-8-21 上午11:50
<fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${now}" />      ----->>> 2012-08-21 11:50:10

<fmt:parseDate>
語法:
<fmt:parseDate value=”dateString” [type=”{time| date|both}”] [dateStyle=”{ default|short|medium|long|full}”] [timeStyle=”{ default|short|medium|long|full}”]
     [pattern=”customPattern ”] [timeZone=”timeZone ”] [parseLocale=”parseLocale”] [var=”varName”]
     [scope=”{page|request|session|application}”]/>
    
描述:
將字符串轉成指定格式的日期和/或時間

例子:
<fmt:parseDate value="20-10-2010" pattern="dd-MM-yyyy" />    ----->>> Wed Oct 20 00:00:00 CST 2010

<fmt:bundle>、<fmt:setBundle>、<fmt:setLocale>
語法:
<fmt:bundle basename=”basename” [prefix=”prefix”]>
body content
</fmt:bundle>
<fmt:setBundle basename=”basename ” [var=”varName”] [scope=”{page|request|session|application}”]/>
<fmt:setLocale value=”locale” [variant=”variant”] [scope=”{page|request|session|application}”]/>

描述:
bundle標簽用於載入一個資源,給其標簽體使用,一般和fmt:message、fmt:setLocale結合使用
setBundle標簽用於載入一個資源,並將資源賦給某一變量
setLocale標簽用於設置語言編碼和國家編碼如(en_US)

例子:
public class Example_En extends ListResourceBundle {
  public Object[][] getContents() {
    return contents;
  }
  static final Object[][] contents = {
  {"count.one", "One"},
  {"count.two", "Two"},
  {"count.three", "Three"},
  };
}

public class Example_es_ES extends ListResourceBundle {
  public Object[][] getContents() {
    return contents;
  }
  static final Object[][] contents = {
  {"count.one", "Uno"},
  {"count.two", "Dos"},
  {"count.three", "Tres"},
  };
}
 
<fmt:bundle basename="com.tutorialspoint.Example">
   <fmt:message key="count.one"/><br/>
   <fmt:message key="count.two"/><br/>
   <fmt:message key="count.three"/><br/>
</fmt:bundle>

<fmt:setLocale value="es_ES"/>
<fmt:bundle basename="com.tutorialspoint.Example">
   <fmt:message key="count.one"/><br/>
   <fmt:message key="count.two"/><br/>
   <fmt:message key="count.three"/><br/>
</fmt:bundle>

<fmt:setBundle basename="com.tutorialspoint.Example" var="lang"/>
<fmt:message key="count.one" bundle="${lang}"/><br/>
<fmt:message key="count.two" bundle="${lang}"/><br/>
<fmt:message key="count.three" bundle="${lang}"/><br/>

<fmt:timeZone>
語法:
<fmt:timeZone value=”timeZone”>
body content
</fmt:timeZone>

描述:
為標簽體內的元素指定時區

例子:
<c:set var="now" value="<%=new java.util.Date()%>" />
<c:forEach var="zone" items="<%=java.util.TimeZone.getAvailableIDs()%>">
    <c:out value="${zone}" />
    <fmt:timeZone value="${zone}">
      <fmt:formatDate value="${now}" type="both" />
    </fmt:timeZone>
</c:forEach>

<fmt:setTimeZone>
語法:
<fmt:setTimeZone value= ”timeZone” [var=”varName”] [scope=”{page|request|session|application}”]/>

描述:
設置時區,並將設置的值存入變量

例子:
<c:set var="now" value="<%=new java.util.Date()%>" />
<fmt:setTimeZone value="GMT-8" />
<fmt:formatDate value="${now}" />

<fmt:message>、<fmt:param>
語法:
<fmt:message key=”messageKey” [bundle=”resourceBundle”] [var=”varName”] [scope=”{page|request|session|application}”]/>
<fmt:message key=”messageKey” [bundle=”resourceBundle”] [var=”varName”] [scope=”{page|request|session|application}”]>
    <fmt:param value="message"/>
</fmt:message>

描述:
從資源文件中根據key讀取鍵值

例子:
public class Example_en extends ListResourceBundle {
  public Object[][] getContents() {
    return contents;
  }
  static final Object[][] contents = {
  {"count.one", "hello {0},welcome!"}
  };
}

<fmt:setLocale value="en"/>
<fmt:setBundle basename="com.tutorialspoint.Example" var="lang"/>
<fmt:message key="count.one" bundle="${lang}">
    <fmt:param value="dengliang"/>
</fmt:message>

<fmt:requestEncoding>
語法:
<fmt:requestEncoding [value= ”charsetName” ]/>

描述:
設置request的字符編碼,用於在頁面解析request傳過來的參數。其實就是在jsp中調用setCharacterEncoding()方法。如果要使用requestEncoding,應該在所有標簽和EL之前設置。

例子:
<fmt:requestEncoding value="UTF-8" />
<fmt:setLocale value="es_ES"/>
<fmt:setBundle basename="com.tutorialspoint.Example" var="lang"/>
<fmt:message key="count.one" bundle="${lang}"/>

JSTL Functions
------------------------------------------------
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

fn:contains()、fn:containsIgnoreCase()
語法:
fn:contains(string, substring) --> boolean
fn:containsIgnoreCase(string, substring) --> boolean

描述:
contains:判斷是否包含某字符串
containsIgnoreCase:和cotains類似,但不區分大小寫

例子:
<c:set var="theString" value="I am a test String"/>
<c:if test="${fn:contains(theString, 'test')}">
   <p>Found test string<p>
</c:if>

fn:endsWith()
語法:
fn:endsWith(string, suffix) --> boolean

描述:
判斷目標字符串是否以某字符串結尾

例子:
<c:set var="theString" value="I am a test String 123"/>
<c:if test="${fn:endsWith(theString, '123')}">
   <p>String ends with 123<p>
</c:if>

fn:escapeXml()
語法:
fn:escapeXml( string) --> String

描述:
忽略字符串中的xml標簽,將xml標簽顯示在頁面

例子:
<c:set var="string2" value="This <abc>is second String.</abc>"/>
${fn:escapeXml(string2)}    ---->>> This <abc>is second String.</abc>

fn:indexOf()
語法:
fn:indexOf(string, substring) --> int

描述:
查詢substring在string中的位置,沒有查到則返回-1

fn:join()
語法:
fn:join( string[], separator) --> String

描述:
用separator將string[]連起來

例子:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:split(string1, ' ')}" />
<c:set var="string3" value="${fn:join(string2, '-')}" />

fn:length()
語法:
fn:length(input) --> int

描述:
返回集合或字符串的長度

fn:replace()
語法:
fn:replace(inputString, beforeSubstring, afterSubstring) --> String

描述:
用afterSubstring替換inputString中的beforeSubstring

fn:split()
語法:
fn:split(string, delimiters ) --> String[]

描述:
用delimiters分隔string,並返回string[]

fn:startsWith()
語法:
fn:startsWith(string, prefix) --> boolean

描述:
判斷string是否以prefix開頭

fn:substring()
語法:
fn:substring( string, beginIndex, endIndex ) --> String

描述:
截取指定長度的字符串

fn:substringAfter()
語法:
fn:substringAfter( string, substring) --> String

描述:
從substring開始截取後面的字符串

例子:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:substringAfter(string1, 'Str')}" />
${string2}         --->>> ing.

fn:substringBefore()
語法:
fn:substringBefore(string, substring) --> String

描述:
從substring開始截取前面的字符串

例子:
<c:set var="string1" value="This is first String."/>
<c:set var="string2" value="${fn:substringBefore(string1, 'irs')}" />
${string2}         --->>> This is f

fn:toLowerCase()
語法:
fn:toLowerCase(string) --> String

描述:
小寫string

fn:toUpperCase()
語法:
fn:toUpperCase(string) → String

描述:
大寫string

fn:trim()
語法:
fn:trim( string) → String

描述:
去掉string兩邊的空格

Scriptlet和JSTL混用
------------------------------------------------
在JSTL中訪問Scriplet中的變量
<%
String myVariable = "Test";
pageContext.setAttribute("myVariable", myVariable);
%>
<c:out value="${myVariable}"/>

在Scriptlet中訪問JSTL中的變量
<c:set var="myVariable" value="Test"/>
<%
String myVariable = (String)pageContext.getAttribute("myVariable");
out.print(myVariable);
%>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved