반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

Yeonee's Story

[JSP] JSTL Core Library - 4. 반복문 - forEach <c:forEach> 본문

⋆ 。゜☁︎ 。⋆ 。゜☾゜。⋆⋆ 。゜☁︎ 。⋆ 。゜☾゜。⋆/JSP

[JSP] JSTL Core Library - 4. 반복문 - forEach <c:forEach>

yeonee 여니 2023. 7. 28. 19:33
728x90
반응형
SMALL

안녕하세요.
https://blog.naver.com/sysysy0302 여니입니다 :)

 

yeonee 블로그 : 네이버 블로그

예쁘고 맛있게 먹고 건강하게,강인하지만 온화하게 행하라. ※맛스타운스타일상 인스타 www.instagram.com/s2._.y25n ※맛집감성일상 유튜브https://youtube.com/channel/@S2_yeonee 티스토리https://yeoneeluv.tistory.co

blog.naver.com

 

 

* JSTL이란?

JSTL(JSP Standard Tag Library)는 JSP에서 유용하게 사용될 수 있는 기능을 만들어 둔 커스텀 태그 라이브러리이다. JSTL을 사용하면 JSTL을 사용하면 JSP에서 스크립틀릿의 사용을 줄일수 있으며, 특히 화면에 데이터를 표현할때 필요한 프로그램 요소를 대체할 수 있어 유용하다.

 

 

4. 반복문 - forEach

- <c:forEach>

    ☆ for loop문 - (&lt;c:forEach var='변수명' begin='초기값' end='종료값' step='증가값(생략가능)' &gt;) <!-- for(int i=0; i<n; i++) -->
  ★☆ 향상된 for문 - (&lt;c:forEach var='변수명' items="순차적으로 접근할 배열또는 컬렉션" varStatus="현재 접근된 요소의 상태값을 보관할 변수명(생략가능)" &gt;
	=> step : 지정하지 않을시 기본값 1
	=> varStatus : 현재 접근된 요소의 상태값을 보관할 변수명(생략가능)

 

예시1)

       <!-- for loop문 -->
	<%
		for(int i=0; i<10; i++){
			
		}
	%>
	
1)	<c:forEach var="i" begin="1" end="10"> 
		반복확인 : ${i } <br>
	</c:forEach>
    
    
2)     <c:forEach var="i" begin="1" end="10" step="2"> 
		반복확인 : ${i } <br>
	</c:forEach>
	
    
3)	<c:forEach var="i" begin="1" end="6">
		<h${i }>태그안에 el 표현식 사용</h${i }>
	</c:forEach>

 

예시2)

        <!-- 향상된 for문. -->
	<c:set var="colors">
		red, yellow, green, pink
	</c:set>
	
	colors 값 : ${colors } <br> <!-- 중간구분자로 ,가 있는 문자열임 -->
	
	<ul>
		<c:forEach var="c" items="${colors }"> <!-- 향상된반복문의 속성값으로 들어가면 배열로서 문자열이 잘라서 값이 들어가서 출력됨. -->
			<li style="color:${c}">${c }</li>
		</c:forEach>
	</ul>

 

예시3)

        <%
		ArrayList<Person> list = new ArrayList(); /* 객체생성 */
		list.add(new Person("도로시",19,"여자"));
		list.add(new Person("테리",20,"남자"));
		list.add(new Person("마틸다",20,"여자"));
		
		request.setAttribute("list", list); // 여기까지가 원래 Servlet에서 작성했어야했을 코드들
	%>
        <table border="1">
		<thead>
			<tr>
				<th>순번</th>
				<th>이름</th>
				<th>나이</th>
				<th>성별</th>
			</tr>
		</thead>
		<tbody>
			<% if(list.isEmpty()) { %>
				<tr	align="center">
					<td colspan="4">조회 결과가 없습니다.</td>
				</tr>
			<% } else { %>	
				<% for(int i=0; i<list.size(); i++) { %>
					<tr>
						<td><%= i %></td>
						<td><%= list.get(i).getName() %></td>
						<td><%= list.get(i).getAge() %></td>
						<td><%= list.get(i).getGender() %></td>
					</tr>
				<% } %>
			<% } %>
		</tbody>
	</table>

자바코드로 작성한 if문(조건문)과 for문(반복문)을 EL로 접근해서 표현해본 코드는 아래의 2가지 경우가 있다.

 

EL로 접근해서 코드를 적은 경우 1)

       <table border="1">
		<thead>
			<tr>
				<th>순번</th>
				<th>이름</th>
				<th>나이</th>
				<th>성별</th>
			</tr>
		</thead>
		<tbody>
			<c:if test="${empty list}">
				<tr	align="center">
					<td colspan="4">조회 결과가 없습니다.</td>
				</tr>
			</c:if>
			<!-- 기본 반복문 -->
			<c:forEach var="i" begin='0' end='${list.size() -1 }'>
				<tr>
					<td>${i }</td>
					<td>${list.get(i).name }</td>
					<td>${list.get(i).age }</td>
					<td>${list.get(i).gender }</td>
				</tr>
			</c:forEach>

 

 

EL로 접근해서 코드를 적은 경우 2)

반복문 바깥에 ver 변수 선언과 value값을 준 뒤, value값을 forEach반복문에 적용한 예이다. 

                        <c:set var="count" value="0"/>	<!-- 바깥쪽에 작성해야함 -->
			
			<c:forEach var="person" items="${list }" varStatus='status'> <!-- list의 값들이 하나씩 person으로 들어가게됨 -->
				<c:set var="count" value="${count + 1 }"/>
				<tr>
					<td>${status.count }</td>
					<!-- 
						status의 속성값
						index : 0부터 시작
						count : 1부터 시작
						first : 첫 반복시 true / 그외 false
						last  : 마지막반복시true / 그외 false	
					-->
					<td>${person.name }</td>
					<td>${person.age }</td>
					<td>${person.gender }</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>

 

 

728x90
반응형
LIST