JSTL ForEach

박병주·2023년 1월 15일
0

EL/JSTL

목록 보기
3/3

반복문은 코드의 중복 제거를 위해 사용된다.
반복문을 이용하면 동일한 작업을 특정 횟수만큼 실행할 수 있다.

jstl에서 흔하게 사용하는 foreach문에 대해서 알아보자.

foreach문을 사용하기 앞서 JSP페이지에 jstl core 선언이 필요하다.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:foreach>

<c:foreach> 는 목록을 입력받아 목록의 갯수만큼 반복하는 반복문이다.

input

@RequestMapping(value = "/practice")
@Controller
public class JstlPracticeController {

    @RequestMapping(value = "/foreach")
    public String forEachParctice(Model model){
        
        ArrayList<String> nameList = new ArrayList<String>();
        nameList.add("이승기");
        nameList.add("신해철");
        nameList.add("김창완");
        nameList.add("이지은");

        model.addAttribute("nameList", nameList);

        return "foreach";
    }
}
  • ArrayList 형태의 객체를 model객체를 통해 foreach.jsp에 넘겨 주었다.

using foreach

    <c:forEach var="name" items="${nameList}" varStatus="status">
        <p>${status.count} : <c:out value="${name}" /></p>
    </c:forEach>
  • name이란 변수를 이용해서 nameList 목록을 반복시킨다.

varStatus

varStatus 속성에 선언된 변수를 통해 반복문의 상태에 대해서 접근할 수 있다.

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

refer : https://thefif19wlsvy.tistory.com/61

profile
Developer

0개의 댓글