Java如何使用 JSTL标记?
该<c:forEach>核心JSTL标签库的标签是一个有用的标签,当我们想要的数据的集合遍历诸如数组。它通常用于以HTML表的形式在我们的网页中呈现表格数据。
在下面的示例中,我们显示天气数据,该数据存储为字符串的二维数组。在声明并初始化具有某些值的数据之后,我们将其放入请求范围。稍后,<c:forEach>标记可以使用数据,逐行对其进行迭代以形成HTML表。我们的天气数据包括日期,状况和高温和低温。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Weather Forecast</title>
</head>
<body>
<%
String[][] data = {
{"Nov 6", "Sunny", "32", "26"},
{"Nov 7", "Sunny", "32", "26"},
{"Nov 8", "Sunny", "32", "26"},
{"Nov 9", "Partly Cloudy", "32", "26"},
{"Nov 10", "Isolated T-Storms", "32", "26"}
};
request.setAttribute("weathers", data);
%>
<strong>5-Days Weather for Denpasar, Indonesia</strong>
<table border="1">
<tr>
<th>DATE</th>
<th>CONDITION</th>
<th>TEMP. HIGH</th>
<th>TEMP. LOW</th>
</tr>
<c:forEach var="weather" items="${weathers}">
<tr>
<td>${weather[0]}</td>
<td>${weather[1]}</td>
<td align="center">${weather[2]}℃</td>
<td align="center">${weather[3]}℃</td>
</tr>
</c:forEach>
</table>
</body>
</html>我们上面的JSP页面创建以下输出:
印度尼西亚登巴萨5天天气
这是web.xml配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- Config here. -->
</web-app>Maven依赖
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/jstl/1.2/jstl-1.2.jar--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>