프로그래밍 언어/자바 웹

<c:choose> 태그를 이용한 실습

· 코딩마이데이

<c:choose> 태그는 JSP 페이지에서 switch문의 기능을 수행하며, 사용 형식은 다음과 같습니다.

<c:choose>

      <c:when test="조건식1"> 본문내용1</c:when>

      <c:when test="조건식"2">본문내용2</c:when>

      ...

      <c:otherwise>본문내용n</c:otherwise>

</c:choose>

 

첫 번째 <c:when> 태그의 조건식1을 체크해서 참이면 본문내용1을 수행하고 만약 거짓이면 다음 <c:when>의 조건식2를 체크해서 참이면 본문내용2를 수행합니다. 모든 조건이 거짓이면 <c:otherwise> 태그의 본문 내용을 수행합니다.

그럼 실습을 통해 알아보겠습니다.

 

1. 다음과 같이 member5.jsp를 작성합니다. <c:choose> 태그를 이용해 name 값의 유무에 따라 다른 결과를 표시합니다. 만약 name 값이 정상적이면 회원 정보를 출력하고 name이 null이거나 빈 문자열이면 오류 메시지를 출력합니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
  request.setCharacterEncoding("UTF-8");
%>  
<c:set  var="id"  value="hong"  scope="page" />
<c:set  var="pwd"  value="1234"  scope="page" />
<c:set  var="name"  value="${'홍길동'}"  scope="page" />
<c:set  var="age"  value="${22}"  scope="page" />
<c:set  var="height"  value="${177}"  scope="page" />
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>회원 정보 출력 창</title>
	</head>
	<body>
		<table align="center" border="1">
			<tr align="center" bgcolor="lightgreen">
				<td width="7%" ><b>아이디</b></td>
		      	<td width="7%" ><b>비밀번호</b></td>
		      	<td width="7%" ><b>이름</b></td>
		      	<td width="7%"><b>나이</b></td>
		      	<td width="7%" ><b>키</b></td>
			</tr>
			<c:choose>
				<%-- <c:when test="${name==null}"> --%>
				<c:when test="${empty name}">
					<tr align="center">
						<td colspan=5>이름을 입력하세요!!</td>
					</tr>
				</c:when>
				<c:otherwise>
					<tr align="center">
				         <td>${id}</td>
				         <td>${pwd}</td>
				         <td>${name}</td>
				         <td>${age}</td>
				         <td>${height}</td>
			      	</tr>
				</c:otherwise>
			</c:choose>
		</table>
	</body>
</html>

 

2. http://localhost:8080/pro14/test03/member5.jsp로 요청합니다. 먼저 name 변수를 정상적으로 선언한 후 브라우저에서 요청 시 회원 정보를 출력합니다.

정상적인 회원 정보 출력 결과

 

3. 이번에는 다음과 같이 name 변수를 주석 처리합니다.

변수 name 주석 처리

 

4. 브라우저에서 재요청 시 오류 메시지를 출력합니다.

오류 메시지 출력!