JSP/JSP 공부

[jsp] == forEach 배열 출력 ==

congs 2023. 5. 10. 11:56

forEach : 반복문


- items : 대상배열, collection
- var : 요소를 저장할 변수 = 임시변수 느낌
- varStatus : 변수.count(개수), 변수.index(주소) = var에 대한 값을 나열

  • count는 1부터 시작 / index는 0부터 시작

 

<%
      String food[] = {"사과", "배", "귤", "바나나", "감", "레몬"};
      request.setAttribute("f", food); 
%>

<c:forEach items="${f   }" var="fname" varStatus="order">
        count : ${order.count }
        index : ${order.index }
        ${fname } <br>
</c:forEach>

 


사용예시

 

-  배열을 만들어서 출력하는 방법

<body>
<%
		String food[] = {"사과", "배", "귤", "바나나", "감", "레몬"};
		request.setAttribute("f", food);
		//f에 food배열을 담기 (가져오는 경우 getAttribute)
%>
	 
     <c:forEach items="${requestScope.f }" var="fname" varStatus="order"> 
     
	 	count : ${order.count } 
	 	index : ${order.index }
	 	${fname } <br>
	 
	 </c:forEach>
</body>

 

 


 

 

- form의 checkbox를 받아서 출력하는 방법


step6-form.jsp, step6-action.jsp 생성
- form태그안에 checkbox 생성
- 주문자 : 이름
-  체크박스의 내용물을 선택하여 action으로 전송
 
  = checkbox에서는 forEach로 checkbox의 값을 배열로 받아 화면에 반복출력

 

==  step6-form.jsp  ==

<body>

	 <form action="step6-action.jsp">
	 	이름 : <input type="text" name="name"> <br>
	 	좋아하는 과일 : 
	 	<input type="checkbox" name="fruit" value="사과"> 사과
	 	<input type="checkbox" name="fruit" value="배"> 배
	 	<input type="checkbox" name="fruit" value="귤"> 귤
	 	<input type="checkbox" name="fruit" value="자몽"> 자몽
	 	<input type="checkbox" name="fruit" value="바나나"> 바나나
	 	<br>
	 	<button type="submit">전송</button>
	 </form>	
	 
</body>

 

==  step6-action.jsp  ==

<body>
	
	이름 : ${param.name } <br>
	좋아하는 과일 : <br>
    
	 <c:forEach items="${paramValues.fruit }" var="fruit" varStatus="order"> 
     
	 	${order.count } ) ${fruit } <br>
        
	 </c:forEach>
	 
</body>

 


- begin, end, var을 사용하는 방법

(1~10 출력하기)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>forEach:1-10출력</title>
</head>
<body>
	
	<%-- <c:forEach begin="시작숫자" end="끝숫자" var="변수"></c:forEach> --%>
	<c:forEach begin="1" end="10" var="num">
		${num }
	</c:forEach>	
</body>
</html>