JSTL和EL介绍

来源:岁月联盟 编辑:exp 时间:2012-08-22

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);
%>