EL表达式(Expression Language)
目的:使Jsp写起来更加简单
语法结构:${expression}
EL表达式用${}表示,可用在所有的HTML和JSP标签中,作用是代替JSP页面中复杂的JAVA代码.
< %=request. getParameter(“username”)% >等价于 ${ param. username }
我们要取得session中储存一个属性username的值,可以利用下列方法:
session.getAttribute("username") 取得username的值,
在EL中则使用下列方法
${sessionScope.username}
注意 <%@ page isELIgnored=”true” %> 表示是否禁用EL语言,TRUE表示禁止.FALSE表示不禁止.JSP2.0中默认的启用EL语言。
EL存取方法
EL存取变量数据的方法很简单,例如:${username}。它的意思是取出某一范围中名称为 username的变量。
因为我们并没有指定哪一个范围的username,所以它会依序从Page、Request、Session、 Application范围查找。
假如途中找到username,就直接回传,不再继续找下去,但是假如全部的范围都没有找到时, 就回传null。
- 属性范围在EL中的名称
Page PageScope
Request RequestScope
Session SessionScope
Application ApplicationScope
一、EL循环取值:
格式:
<c:forEach items="${messages}"
var="item"
begin="0"
end="9"
step="1"
varStatus="var">
……
</c:forEach>
例如:
allCost是一个list
<c:forEach items="${historyAll}" var="allCost"> //
<div class="form-group" >
<!-- 记录 -->
<label class="col-md-3 control-label margin-3" id ="historyTime">
<fmt:formatDate value="${allCost.sysTime}" type="both" /> </label>
<span class="col-md-3 control-label" id="historyPond">
<c:if test="${allCost.pondid == 1}">aa</c:if>
<c:if test="${allCost.pondid == 2}">bb</c:if>
<c:if test="${allCost.pondid == 3}">cc</c:if></span>
<span class="col-md-2 control-label span_danger margin-3" id="historyValue">${allCost.value}</span>
<span class="col-md-1 control-label margin-5">元</span>
</div>
</c:forEach>
</div>
二、EL条件判断
IF / CHOOSE:
<c:if test="${var.index % 2 == 0}">
</c:if>
例如:
<c:if test="${allCost.pondid == 1}">aa</c:if>
判定条件一般为一个EL表达式。
<c:if>
并没有提供else子句,使用的时候可能有些不便,此时我们可以通过<c:choose>
tag来达到类似的目的:
<c:choose>
<c:when test="${var.index % 2 == 0}">
****
</c:when>
<c:otherwise>
!!!!
</c:otherwise>
</c:choose>
类似Java 中的switch 语句,<c:choose>
提供了复杂判定条件下的简化处理手法。其 中<c:when>
子句类似case子句,可以出现多次。上面的代码,在奇数行时输出“*”号, 而偶数行时输出“!”。
三、fmt格式化标签
注意:需要导入 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
(1)格式化日期
<fmt:formatDate value="" pattern="yyyy-MM-dd HH:mm:ss"/>
Value:通过EL表达式或<%new Date() %> 取的日期值;
Pattern:输出的日期格式;
日期格式化标签:
【fmt:formatData type="date" 默认】2013-6-13
【fmt:formatData type="time"】21:28:08
【fmt:formatData type="both"】2013-6-13 21:28:08
【fmt:formatData pattern="yyyy/MM/dd HH:mm:ss"】2013/06/13 21:28:08
【fmt:formatData dateStyle="short"】13-6-13
【fmt:formatData dateStyle="medium"】2013-6-13
【fmt:formatData dateStyle="long"】2013年6月13日
【fmt:formatData dateStyle="full"】2013年6月13日 星期四
例如:
日期格式(2008年5月5日22点00分23秒):
<fmt:formatDate value="<%=new Date() %>" pattern="yyyy年MM月dd日HH点mm分ss秒" />
(2)格式化数字
<fmt:formatNumber
value="${n}" pattern="###,###.##" />
例如:
保留两位小数:<fmt:formatNumber value="123.123456789" pattern="0.00"/>
格式化数字(45,678.234):<fmt:formatNumber type="number" value="45678.2345" />
格式百分比(23%):<fmt:formatNumber type="percent" value="0.2345" />