본문 바로가기
BackEnd/JAVA

[JAVA] JSTL이란? JSTL의 if문 / if ~ else 문

by 성은2 2020. 9. 25.

1. JSTL 

자바서버 페이지 표준태그 라이브러리(JavaServer Pages Standard Tag Library), JSTL

 

JSTL은 JSP 페이지 내에서 자바 코드를 바로 사용하지 않고 로직을 내장하는 효율적인 방법을 제공한다. 

표준화된 태그 셋을 사용하여 자바 코드의 언급을 줄일 수 있어 유지보수가 용이해진다.

 

 

 

 

2. 사용법

JSTL은 라이브러리이기 때문에 사용하기전에 header에 추가해주어야 한다.

태그 라이브러리 종류 선언문
Core <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
XML <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
I18N <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Database <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Functions <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

코어 태그는 가장 일반적으로 사용되는 JSTL 태그이다. 

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

prefix : JSTL 태그를 사용할때 태그 이름 앞에 붙일 접두사

ex) <c:if>  , <c:choose>

 

 

 

 

3. JSTL의 core 태그 (자주 사용 - if, switch, for 개념)

태그 설명
<c:out> 값 출력
<c:set> 값 세팅
<c:if> if 문
<c:choose>
    <c:when>
    <c:when/> 
    <c:otherwise>
    <c:otherwise/> 
<c:choose/>
switch문과 비슷

<c:forEach> 반복문, items속성에 배열을 할당할 수 있음

 

* 공식 문서 표 참고

<c: out> For displaying data in a JSP, like <% = ...>
<c: set> For holding data
<c: remove> For deleting data
<c: catch> To handle error exception condition, and an error message store
<c: if> And if we are in the same general procedure used
<c: choose> Itself only as <c: when> and <c: otherwise> parent tag
<c: when> <C: choose> sub-tab is used to determine whether the conditions established
<c: otherwise> <C: choose> sub-tab, then in <c: when> tag after, when <c: when> tag is judged as false is executed
<c: import> Retrieving an absolute or relative URL, and then exposed to the contents page
<c: forEach> Iterative label basis, accept a variety of collection types
<c: forTokens> According to the specified delimiter to separate content and iterative output
<c: param> It used to contain or redirect the page to pass parameters
<c: redirect> Redirected to a new URL.
<c: url> Use the optional query parameters to create a URL

 

 

 

JSTL의 if 문 :  <c:if>

 : else가 없는 단순 if문을 구성할 때 사용

<c:set var="name" value="홍길동" />

<c:if test="${name eq '홍길동'}"> // eq : equal, 같다면
홍길동 입니다.
</c:if>

 

 

 

JSTL의 if ~ else 문 :  <c:choose> <c:when> <c:otherwise>

 : if ~ else 처럼 여러 조건을 주고 싶을 때

 

* 게시글 목록 예제

: 서버에서 보내는 list 값이 있는 경우 (0보다 크면) ,

list의 MEMBER_ID, REGDATE 등의 데이터를 반복하여 출력하는 예제

: 그 외에는(otherwise) "조회된 결과가 없습니다" 라는 문자열 출력

<c:choose>
	<c:when test="${fn:length(list) > 0}">
		<c:forEach var="row" items="${list}" varStatus="s">
			<tr>
				<td>${row.RNUM}</td>
				<td class="title"><a href="#this" name="title">${row.TITLE}</a>
					<input type="hidden" id="BOARD_NO" value="${row.BOARD_NO}">
				</td>
				<td>${row.MEMBER_ID}</td>
				<td>${row.REGDATE}</td>
			</tr>
		</c:forEach>
	</c:when>
	<c:otherwise>
		<tr>
			<td colspan="4">조회된 결과가 없습니다.</td>
		</tr>
	</c:otherwise>
</c:choose>

 

 

JSTL의 반복문 : forEach

: List만큼 반복, 주로 List를 화면에 뿌릴 때 사용

<ul>
<c:forEach var="vo" items="${list}">		
	<li>
	<div>
		<p class="title">${vo.title} ${vo.subTitle}</p>
		<p class="info">${vo.useDt}</p>
	</div>
	<div>
		<c:choose>
			<c:when test="${vo.useYn eq 'Y' }">
				<p class="point"><span class="plus"></span> ${vo.point}점</p>
			</c:when>
            <c:when test="${vo.useYn eq 'N' }">
				<p class="point"><span class="minus"></span> ${vo.point}점</p>
			</c:when>
			<c:otherwise>
				<p class="point"><span class="minus"></span> 없음 </p>
			</c:otherwise>
		</c:choose>
	</div>
	</li>
</c:forEach>
</ul>

 

 

 

 

4. 비교 기호

: eq, ne, empty

 

* eq :  (==) 비교하고자 하는 값이 같으면 (=equal)

* ne  : (!=)  비교하는 값이 같지 않으면 (=not equal)

* empty  : (==null) 비교하는 값이 null이면

* not empty  : (!=null) 비교하는 값이 null이 아니면

 

<c:set var="list" value="${testList}"/> // 변수 세팅
<c:if test="${!empty list}"> // list가 빈 값이 아니면(!)
	<c:forEach var="occu" items="${testList}">
		$('select[id=id_'+"${occu.code}"+'] option:eq(0)').prop("selected", true);
	</c:forEach>
</c:if>

 

<c:choose>
	<c:when test="${!empty mem}">
		${mem.MEMBER_ID}님 반갑습니다!
	</c:when>
	<c:otherwise>
		회원가입 하러가기
	</c:otherwise>
</c:choose>

 

 

 

 

[내장 객체]

  • 내장 객체(implicit object)는 JSP 페이지에서 사용할 수 있도록 JSP 컨테이너에 미리 정의된 객체로 그 종류가 다양함
  • JSP 페이지가 서블릿 프로그램으로 번역될 때 JSP 컨테이너가 자동으로 내장 객체를 멤버 변수, 메소드 매개변수 등의 각종 참조 변수(객체)로 포함시킴
    - JSP 에서 별도의 import문 없이 자유롭게 사용할 수 있음
    - 스크립틀릿 태그나 표현문 태그에 선언을 하거나 객체를 생성하지 않고도 직접 호출하여 사용할 수 있음

 

 

 

-JSP 내장객체 종류

pageContext : 다른 내장 객체를 생성하는 역할

pageScope : JSP가 Servlet으로 변환되었을 때, Serlvet 객체 자신을 의미 (=this)

requestScope :  request 객체에 접근하기 위한 역할

sessionScope :  session객체에 접근하기 위한 역할

applicationScope : application 객체 (ServletContext 객체)에 접근하기 위한 역할

 

 

 

 

세션에 설정한 Attribute 값 JSTL로 사용하기

위와 같이 sessionScope라는 내장 객체를 통해 JSP에서 세션값을 사용할 수 있다.

HttpSession Session = request.getSession(true);

Session.setAttribute("memId", "testid1234");

 

<input type="text" id="memberId" value="${sessionScope.memId}"/>

 

 

 

 

 

 

출처 : daesuni.github.io/jstl/

 

JSTL의 기본 개념과 사용방법 정리

1. JSTL이란?

daesuni.github.io

출처 : fruitdev.tistory.com/131

 

JSTL IF ~ ELSE 문 - 와

JSTL에도 IF문과 같은 분기문을 기본으로 제공하는데, 우리가 사용하는 것과는 약간 내용상 차이가 있다. 우리는 보통 IF문을 사용할때 IF ~ ELSE IF ~ ELSE 를 이용하여 프로그래밍 코드를 작성하는데,

fruitdev.tistory.com