四、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>