본문 바로가기
Spring/JSP

[JSP] JSTL <c:forEach>

by JJH0100 2022. 11. 24.
728x90
반응형

선언문

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

 

형식

<c:forEach var="변수명" items="${배열이름}" varStatus="상태용변수명">
    반복할 구문
</c:forEach>

 

상태용변수

${status.current} 현재 for문에 해당하는 번호
${status.index} 0부터 순서
${status.count} 1부터 순서
${status.first} 첫번째
${status.last} 마지막
${status.begin} for문 시작 번호
${status.end} for문 끝번호
${status.step} for문 증가값

 


 

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	String[] movieList = {"범죄도시2",  "타이타닉", "아이언맨", "킹콩", "어벤져스"};
	pageContext.setAttribute("movieList", movieList);
%>
<table border="1" style="width:100%; text-align:center;" >
	<tr>
		<th>index</th>
		<th>count</th>
		<th>title</th>
	</tr>
	<c:forEach var="movie" items="${movieList}" varStatus="status">
		<tr>
			<th>${status.index}</th>
			<th>${status.count}</th>
			<th>${movie}</th>
		</tr>
	</c:forEach>
</table>
<hr>
<ul>
	<c:forEach var="movie" items="${movieList}" varStatus="status">
		<c:choose>
			<c:when test="${status.first}">
				<li style="font-weight:bold; color:red;">${movie}</li>
			</c:when>
			<c:otherwise>
				<li>${movie}</li>
			</c:otherwise>
		</c:choose>
	</c:forEach>
</ul>
<hr>
<c:forEach var="movie" items="${movieList}" varStatus="status">
	<c:choose>
		<c:when test="${status.last}">
			${movie}
		</c:when>
		<c:otherwise>
			${movie}, 
		</c:otherwise>
	</c:choose>
</c:forEach>
</body>
</html>

728x90
반응형

'Spring > JSP' 카테고리의 다른 글

[JSP] 파일전송  (0) 2022.11.28
[JSP] JSTL <c:if>  (0) 2022.11.24
[JSP] JSTL - Core  (0) 2022.11.24
[JSP] JSTL 설치  (0) 2022.11.24
[JSP] 로그인 예제  (0) 2022.11.23

댓글