JSTL 튜토리얼, JSTL 태그 예제


JSTL은 JSP 표준 태그 라이브러리를 나타냅니다. JSTL은 JSP 페이지 동작을 제어하는 태그를 제공하는 표준 태그 라이브러리입니다. JSTL 태그는 반복 및 제어 문, 국제화, SQL 등에 사용할 수 있습니다. 이 JSTL 자습서에서 JSTL 태그를 자세히 살펴보겠습니다. 앞서 우리는 JSP Action Tags를 사용하여 HTML과 같은 JSP 코드를 작성하는 방법을 살펴보았지만 그 기능은 매우 제한적입니다. 예를 들어, EL 또는 action 요소를 사용하여 컬렉션을 반복할 수 없으며 HTML 태그를 이스케이프하여 클라이언트 측에서 텍스트처럼 표시할 수 없습니다. JSTL 태그에서 훨씬 더 많은 작업을 수행할 수 있으므로 JSTL 태그가 유용합니다.

JSTL

JSTL 항아리

JSTL jar는 컨테이너별로 다릅니다. 예를 들어 Tomcat에서는 프로젝트 빌드 경로에 jstl.jarstandard.jar jar 파일을 포함해야 합니다. 컨테이너 lib 디렉터리에 없는 경우 애플리케이션에 포함해야 합니다. maven 프로젝트가 있는 경우 pom.xml 파일에 아래 종속성을 추가해야 합니다. 그렇지 않으면 JSP 페이지에서 다음 오류가 발생합니다. - eclipse Can not find the tag library descriptor for \https:/ /java.sun.com/jsp/jstl/코어

<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 기능을 기반으로 5가지 유형으로 분류된다.

  1. JSTL Core Tags: JSTL Core tags provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc. To use JSTL core tags, we should include it in the JSP page like below.

    <%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
    

    In this article, we will look into important JSTL core tags.

  2. JSTL Formatting and Localisation Tags: JSTL Formatting tags are provided for formatting of Numbers, Dates and i18n support through locales and resource bundles. We can include these jstl tags in JSP with below syntax:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    
  3. JSTL SQL Tags: JSTL SQL Tags provide support for interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags we can run database queries, we include these JSTL tags in JSP with below syntax:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    
  4. JSTL XML Tags: JSTL XML tags are used to work with XML documents such as parsing XML, transforming XML data and XPath expressions evaluation. Syntax to include JSTL XML tags in JSP page is:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/xml" prefix="x" %>
    
  5. JSTL Functions Tags: JSTL tags provide a number of functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc. Syntax to include JSTL functions in JSP page is:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    

모든 JSTL 표준 태그 URI는 https://java.sun.com/jsp/jstl/로 시작하며 원하는 모든 접두사를 사용할 수 있지만 위에 정의된 접두사를 사용하는 것이 가장 좋습니다. 모두가 그것들을 사용하므로 혼란을 일으키지 않을 것입니다.

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

JSTL 튜토리얼

JSTL 튜토리얼 - 자바 빈 클래스

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;
	}

}

JSTL 튜토리얼 - 서블릿 클래스

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);
	}

}

JSTL 튜토리얼 - JSP 페이지

home.jsp 코드:

<%@ 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>