四、JSTL的用法
在平常的使用中我们一般利用 EL 控制变量以及变量的输出,利用 JSTL 控制算术逻辑。 JSTL 是一种标记。
1. JSTL 的导入
i. 手动导入架包,填写真实的 uri=http://java.sun.com/products/jsp/jst1
ii. 利用 Myeclipse 导入架包,填写的 uri 也变成相对路径
2. JSTL 中的流程控制
a) 条件处理
例如:(就算是 String 类型的也是利用 = = 判断是否相同)
<c:if test=”${x==9}”>
${x}
</c:if>
例如:
<c:choose>
<c:when text=” ${x==9}”>
This is when term
</c:when>
<c:otherwise>
This is otherwise term
</c:otherwise>
</c:choose>
b) 循环控制
普通循环:
<c:forEach var=”x” begin=” 1” end=”9”>
${x}
</c:forEach>
数组等遍历:
<h3> 遍历数组 </h3>
<%int[] sss = {22,34,21};
pageContext.setAttribute("ss", sss, PageContext.PAGE_SCOPE);
for(int s:sss){
out.print(s);
}
%>
<fw:forEach items="${ss}" var="s">
${s }
</fw:forEach>
<h3> 遍历简单类型的集合 </h3>
<%List<String> list = new ArrayList<String>();
list.add("fw"); list.add("jr");
pageContext.setAttribute("ll", list, PageContext.PAGE_SCOPE);
for(String l:list){
out.print(l);
}
%>
<fw:forEach items="${ll}" var="l">
${l }
</fw:forEach>
<h3> 遍历复杂类型的集合 </h3>
<%List<User> userList = new ArrayList<User>();
userList.add(new User(1,"mm"));
userList.add(new User(2,"mjj"));
pageContext.setAttribute("ul", userList, PageContext.PAGE_SCOPE);
for(User u:userList){
out.print(u.getId()+" "+u.getName());
}
%>
<fw:forEach items="${ul}" var="u">
id:${u.id } name:${u.name }
</fw:forEach>
<h3>MAP 的遍历 </h3>
<%
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"jjj");
map.put(2,"rrr");
pageContext.setAttribute("map", map, PageContext.PAGE_SCOPE);
%>
<fw:forEach items="${map}" var="m">
键 :${m.key } 值 :${m.value }<br>
</fw:forEach>
<jr:formatNumber maxFractionDigits="2">
45.7891234
</jr:formatNumber>