6.24 JSP学习
- JSTL 标签库
JSTL标签库允许开发人员可以像使用HTML标签那样在JSP中开发java功能
- 导包 : jstl.jar 和 standard.jar
- set out remove (jstl 标签库里到底有哪些标签)
(reference : https://www.cnblogs.com/zhangyinhua/p/7637399.html#_lab2_1_3)
i) 如果你想在jsp中使用JSTL标签库, 那么就要进行标签库指令设置
<%@ taglib uri = “http://java.sun.com/jsp/jstl/core” prefix = “c” %>
然后如果想使用JSTL标签库时, 语句开始都要以<c: 开头
e.g. :
a) <c: set var=”name” value=” ‘ g r e e n ’ ” s c o p e = “ r e q u e s t ” / > 相 当 于 < b ) < c : o u t v a l u e = “ {‘green’ }” scope = “request” /> 相当于 <% request.setAttribute(“name” ,”green”) %> b) <c: out value = “ ‘green’”scope=“request”/>相当于<b)<c:outvalue=“{name}” />
相当于<%=request.getAttribute(“name”) %>
c) <c: remove var= “name” scope = “request”>
相当于<%request.removeAttribute(“name”)%>
(作用域可以是pageContext, request, session, application等等)
ii) if else
a) JSTL通过<c: if test=””> 进行条件判断, 但是没有else 就只能通过取反判断了.
b) 还可以通过使用empty进行空判断.()
c) Example
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" errorPage="catch.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="hp" value="${10}" scope="request" />
<c:if test="${hp>5}">
<p>Han is going to the hell.</p>
</c:if>
<c:if test="${!hp>5}">
<p>Han is still alive.</p>
</c:if>
<c:if test = "${empty weapon}">
<p> 没有武器 ! </p>
</c:if>
- forEach 来替换JSP中的for循环
i) forEach的用法 : 循环语句
ii) 解析 : items=”{heros}” 表示遍历集合
var = “hero” 表示把每一个集合中的元素放在hero上
varStatus=”st” 表示遍历的状态
iii) 范例
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- 使用JSTL中的c:forEach循环来遍历List -->
<%
List<String> heros = new ArrayList<String>();
heros.add("Han1");
heros.add("Han2");
heros.add("Han3");
heros.add("Han4");
request.setAttribute("heros", heros);
%>
<table width="200px" align="center" border="1" cellspacing="0">
<tr>
<td>编号</td>
<td>英雄</td>
</tr>
<%
System.out.println("part1");
%>
<c:forEach items="${heros}" var="hero" varStatus="st">
<%
System.out.println("part2");
%>
<tr>
<td><c:out value="${st.count }" /></td>
<td><c:out value="${hero}" /></td>
</tr>
</c:forEach>
</table>