JSTL 代表JSP 标准标签库。 JSTL 是标准标记库,它提供标记来控制 JSP 页面行为。 JSTL 标签可用于迭代和控制语句、国际化、SQL 等。我们将在本 JSTL 教程中详细研究 JSTL 标签。之前我们看到了如何使用JSP EL and JSP 操作标签像HTML一样编写JSP代码,但它们的功能非常有限。例如,我们无法使用 EL 或操作元素循环遍历集合,也无法转义 HTML 标签以将它们像客户端中的文本一样显示。这就是 JSTL 标签派上用场的地方,因为我们可以通过 JSTL 标签做更多事情。
JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container. Most of the times, you can find them in the example projects of server download and you can use them. You need to include these libraries in your web application project WEB-INF/lib directory.
JSTL jar 是特定于容器的,例如在 Tomcat 中,我们需要包含jstl.jar
and standard.jar
项目构建路径中的 jar 文件。如果它们不存在于容器 lib 目录中,您应该将它们包含到您的应用程序中。如果您有maven项目,则应添加以下依赖项pom.xml
文件,否则您将在 JSP 页面中收到以下错误 -eclipse Can not find the tag library descriptor for "https://java.sun.com/jsp/jstl/ core"
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
根据 JSTL 功能,它们分为五种类型。
-
JSTL 核心标签:JSTL核心标签提供对迭代、条件逻辑、捕获异常、url、转发或重定向响应等的支持。要使用JSTL核心标签,我们应该将其包含在JSP页面中,如下所示。
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
在本文中,我们将研究重要的 JSTL 核心标签。
-
JSTL 格式化和本地化标签:提供 JSTL 格式化标签,用于通过区域设置和资源包格式化数字、日期和 i18n 支持。我们可以使用以下语法在 JSP 中包含这些 jstl 标记:
<%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
-
JSTL SQL 标签:JSTL SQL 标签提供与关系数据库(如 Oracle、MySql 等)交互的支持。使用 JSTL SQL 标签我们可以运行数据库查询,我们在 JSP 中包含这些 JSTL 标签,语法如下:
<%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
-
JSTL XML 标签:JSTL XML 标签用于处理 XML 文档,例如解析 XML、转换 XML 数据和 XPath 表达式评估。在 JSP 页面中包含 JSTL XML 标记的语法是:
<%@ taglib uri="https://java.sun.com/jsp/jstl/xml" prefix="x" %>
-
JSTL 函数标签:JSTL标签提供了许多我们可以用来执行常见操作的函数,其中大多数用于字符串操作,例如字符串连接,分割字符串等。在JSP页面中包含JSTL函数的语法是:
<%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>
请注意,所有 JSTL 标准标记 URI 都以https://java.sun.com/jsp/jstl/
我们可以使用任何我们想要的前缀,但最好的做法是使用上面定义的前缀,因为每个人都使用它们,所以它不会造成任何混乱。
JSTL 核心标签列于下表中。
JSTL Core Tag |
Description |
<c:out> |
To write something in JSP page, we can use EL also with this tag |
<c:import> |
Same as jsp:include or include directive |
<c:redirect> |
redirect request to another resource |
<c:set> |
To set the variable value in given scope. |
<c:remove> |
To remove the variable from given scope |
<c:catch> |
To catch the exception and wrap it into an object. |
<c:if> |
Simple conditional logic, used with EL and we can use it to process the exception from <c:catch> |
<c:choose> |
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <c:when> and <c:otherwise> |
<c:when> |
Subtag of <c:choose> that includes its body if its condition evalutes to ‘true’. |
<c:otherwise> |
Subtag of <c:choose> that includes its body if its condition evalutes to ‘false’. |
<c:forEach> |
for iteration over a collection |
<c:forTokens> |
for iteration over tokens separated by a delimiter. |
<c:param> |
used with <c:import> to pass parameters |
<c:url> |
to create a URL with optional query string parameters |
Let’s see some of the JSTL core tags usages in a simple web application. Our project will include a Java Bean and we will create a list of objects and set some attributes that will be used in the JSP. JSP page will show how to iterate over a collection, using conditional logic with EL and some other common usage.
package com.journaldev.model;
public class Employee {
private int id;
private String name;
private String role;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
package com.journaldev.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.journaldev.model.Employee;
@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Employee> empList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setId(1); emp1.setName("Pankaj");emp1.setRole("Developer");
Employee emp2 = new Employee();
emp2.setId(2); emp2.setName("Meghna");emp2.setRole("Manager");
empList.add(emp1);empList.add(emp2);
request.setAttribute("empList", empList);
request.setAttribute("htmlTagData", "<br/> creates a new line.");
request.setAttribute("url", "https://www.journaldev.com");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");
rd.forward(request, response);
}
}
home.jsp
code:
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<style>
table,th,td
{
border:1px solid black;
}
</style>
</head>
<body>
<%-- Using JSTL forEach and out to loop a list and display items in table --%>
<table>
<tbody>
<tr><th>ID</th><th>Name</th><th>Role</th></tr>
<c:forEach items="${requestScope.empList}" var="emp">
<tr><td><c:out value="${emp.id}"></c:out></td>
<td><c:out value="${emp.name}"></c:out></td>
<td><c:out value="${emp.role}"></c:out></td></tr>
</c:forEach>
</tbody>
</table>
<br><br>
<%-- simple c:if and c:out example with HTML escaping --%>
<c:if test="${requestScope.htmlTagData ne null }">
<c:out value="${requestScope.htmlTagData}" escapeXml="true"></c:out>
</c:if>
<br><br>
<%-- c:set example to set variable value --%>
<c:set var="id" value="5" scope="request"></c:set>
<c:out value="${requestScope.id }" ></c:out>
<br><br>
<%-- c:catch example --%>
<c:catch var ="exception">
<% int x = 5/0;%>
</c:catch>
<c:if test = "${exception ne null}">
<p>Exception is : ${exception} <br>
Exception Message: ${exception.message}</p>
</c:if>
<br><br>
<%-- c:url example --%>
<a href="<c:url value="${requestScope.url }"></c:url>">JournalDev</a>
</body>
</html>
Now when we run application with URL https://localhost:8080/JSTLExample/HomeServlet
, we get response as in below image. In above JSTL example, we are using c:catch
to catch the exception within the JSP service method, it’s different from the JSP Exception Handling with error pages configurations. That’s all for a quick roundup of JSTL tags and example of JSTL core tags usage. Reference: JSTL Wikipedia Page