JSTL(JavaServer Pages Standard Tag Library)
- JSP에서 자주 쓰이는 작업(조건문, 반복문, 포맷팅 등)을 처리하는 태그 라이브러리
- 이를 통해 Java 코드를 JSP에 직접 작성하지 않고 XML 기반 태그로 더 간결하게 표현 가능
- 보통 <%@ taglib %> 디렉티브를 통해 선언
주요 JSTL 태그
- Core 태그(c 태그) : 조건문, 반복문 등 핵심적인 기능 제공
- <c:if> : 조건에 따라 내용 표시
- <c:choose>, <c:when>, <c:otherwise> : 조건 분기
- <c:forEach> : 반복 처리
- <c:set> : 변수 변경
- <c:out> : 값을 화면에 출력
<%-- 조건문 사용 예시 --%>
<c:if test="${user != null}">
<p>Welcome, ${user.name}</p>
</c:if>
<%-- 반복문 사용 예시 --%>
<c:forEach var="item" items="${items}">
<p>${item}</p>
</c:forEach>
- Formatting 태그(fmt 태그) : 날짜나 숫자 등의 형식 지정
- <fmt:formatDate> : 날짜 형식 지정
- <fmt:formatNumber> : 숫자 형식 지정
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd"/>
- Functions 태그(fn 태그) : 문자열 조작 함수 포함
- fn:length : 문자열 길이
- fn:contains : 특정 문자열 포함 여부
<c:if test="${fn:contains(name, 'John')}">
<p>Hello, John!</p>
</c:if>
EL(Expression Language)
- JSP에서 Java 객체에 접근해 데이터를 출력하거나 조건을 처리할 때 사용
- ${} 형식으로 데이터 참조
EL의 주요 특징
- 데이터 접근 : 페이지, 요청, 세션, 어플리케이션 범위에 저장된 데이터에 접근
${user.name}
${sessionScope.cart.items}
- 연산자 지원 : 논리, 비교, 산술
- 산술 : +, -, *, /, %
- 비교 : ==, !=, <, >, <=, >=
- 논리 : &&, ||, !
<c:if test="${user.age >= 18}">
<p>Adult</p>
</c:if>
- 기본 객체 : 미리 정의된 객체들이 있어 각종 정보에 쉽게 접근 가능
- param : 요청 파라미터 값(param.name은 name의 파라미터 값)
- sessionScope, requestScope, applicationScope : 각 범위 내의 객체에 접근
- header, cookie, initParam : HTTP 헤더, 쿠키, 초기화 파라미터에 접근
${param.username}
${sessionScope.user}
- null처리 : null값을 빈 문자열로 처리하거나 조건에서 false로 간주
<c:if test="${empty param.username}">
<p>Username is required.</p>
</c:if>
JSTL과 EL 사용 예제
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:choose>
<c:when test="${user != null}">
<p>Welcome, ${user.name}!</p>
</c:when>
<c:otherwise>
<p>Please log in.</p>
</c:otherwise>
</c:choose>
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<c:forEach var="post" items="${posts}">
<tr>
<td>${post.title}</td>
<td>${post.author}</td>
</tr>
</c:forEach>
</tbody>
</table>
<a href="/page/1" class="${page == 1 ? 'current' : ''}">1</a>
<a href="/page/2" class="${page == 2 ? 'current' : ''}">2</a>