JSTL和EL介绍
jstl规范介绍
------------------------------------------------
jstl:
* jstl即jsp standard tag library的缩写
* 一些常用的jsp标签
* 和mvc框架结合使用很方便,如果struts、spring m
* 不是jsp 1.2,2.0,2.1规范的一部分,需要单独下载。下表是servlet、、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="https://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="https://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="https://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="https://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="https://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);
%>