본문 바로가기
Java/Servlet & JSP

JSP) 분기처리 - if문/switch문/반복처리

by 박채니 2022. 6. 17.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


분기

 

<ul>
    <li><a href="/web2/jsp/basic.jsp?lang=en">JSP Basic</a></li>
</ul>

사용자가 페이지에 접속할 때 lang를 선택하여 들어올 수 있다고 가정해보겠습니다.

lang이 'en'이라면, 'Hello'가 lang이 'ko'라면 '안녕'이 나타나보도록 하겠습니다.


if문

<h2>분기</h2>
<%
    String lang = request.getParameter("lang");
    System.out.println("lang = " + lang);

    if("en".equals(lang)) {
%>
    <p>Hello!</p>
<%
    } else if("ko".equals(lang)) {
%>
    <p>안녕하세요!</p>;
<%
    }
%>

lang = en일 경우

 

lang = ko일 경우

<% %>는 자바 코드 공간이므로 위처럼 분기 처리를 할 수 있습니다.

 

페이지 소스 보기

lang='ko'일 경우에는 'Hello'에 대한 코드는 찾아볼 수 없는 것을 알 수 있습니다.

 

basic_jsp.java파일의 _jspService 메소드

if("en".equals(lang)) {

out.write("\r\n");
out.write("		<p>Hello!</p>\r\n");
out.write("	");

} else if("ko".equals(lang)) {

out.write("\r\n");
out.write("		<p>안녕하세요!</p>\r\n");
out.write("	");

}

위처럼 변환된 후 처리 되었기 때문에 위와 같은 결과가 나오는 것을 알 수 있습니다.

 


switch문

<%
    switch(lang) {
    case "en" :
%>
    <p>ByeBye~</p>
<%
    break;
    case "ko" :
%>
    <p>잘가요~</p>
<%
    break;
    }
%>

 

lang = en일 경우

 

lang = ko일 경우

 

basic_jsp.java파일의 _jspService 메소드

switch(lang) {
case "en" :

out.write("\r\n");
out.write("		<p>ByeBye~</p>\r\n");
out.write("	");

break;
case "ko" :

out.write("\r\n");
out.write("		<p>잘가요~</p>\r\n");
out.write("	");

break;
}

반복처리

<!-- 임포트 필수 -->
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>

<h2>반복처리</h2>
<ul>
<%
    List<String> names = Arrays.asList("홍길동", "신사임당", "이순신");
    for(String name : names) {
%>
    <li><%= name %></li>
<%
    }
%>
</ul>

이름을 List에 담아 for-each문을 이용하여 이름을 가져왔습니다.

분기처리와 동일한 매커니즘을 갖고 있습니다. 또한 ul태그를 for문 안에 넣게 되면 매번 새로운 ul태그가 생성되므로 ul태그를 for문 시작 전으로 빼주었습니다.

 

basic_jsp.jsp의 _jspService 메소드 확인

List<String> names = Arrays.asList("홍길동", "신사임당", "이순신");
for(String name : names) {

    out.write("\r\n");
    out.write("		<li>");
    out.print( name );
    out.write("</li>\r\n");
    out.write("	");

}

 

@실습문제 - 주문

아래처럼 사용자 입력 값이 넘어온다고 가정!

<ul>
    <li><a href="/web2/jsp/basic.jsp?lang=en">JSP Basic</a></li>
    <li>
        <a href="/web2/jsp/basic.jsp?lang=ko&no=1&prod=아이디어패드&option=빨강&option=128gb">
            @실습문제 - 주문1
        </a>
    </li>
    <li>
        <a href="/web2/jsp/basic.jsp?lang=ko&no=2&prod=설렁탕&option=다대기많이&option=곱빼기&option=소면빼고">
            @실습문제 - 주문2
        </a>
    </li>
</ul>

 

<style>
table {
	border:1px solid #000;
	border-collapse: collapse;
	margin: 10px 0;
}
th, td {
	border:1px solid #000;
	padding: 5px;
}
</style>


<h2>@실습문제 - 주문</h2>
<table>
    <tbody>
        <tr>
            <th>주문번호</th>
            <td><%= request.getParameter("no") %></td>
        </tr>
        <tr>
            <th>상품명</th>
            <td><%= request.getParameter("prod") %></td>
        </tr>
        <%
            String[] options = request.getParameterValues("option");
            if(options != null) {
                for(int i = 0; i < options.length; i++) {
        %>
            <tr>
                <th>옵션 <%= i+1 %></th>
                <td><%=options[i] %></td>
            </tr>
        <%
                }
            }
        %>
    </tbody>
</table>

 

주문 1 접속 시

 

주문 2 접속 시

 

basic_jsp.jsp의 _jspService 메소드 확인

out.write("\r\n");
out.write("	</ul>\r\n");
out.write("	\r\n");
out.write("	<h2>@실습문제 - 주문</h2>\r\n");
out.write("	<table>\r\n");
out.write("		<tbody>\r\n");
out.write("			<tr>\r\n");
out.write("				<th>주문번호</th>\r\n");
out.write("				<td>");
out.print( request.getParameter("no") );
out.write("</td>\r\n");
out.write("			</tr>\r\n");
out.write("			<tr>\r\n");
out.write("				<th>상품명</th>\r\n");
out.write("				<td>");
out.print( request.getParameter("prod") );
out.write("</td>\r\n");
out.write("			</tr>\r\n");
out.write("			");

        String[] options = request.getParameterValues("option");
        if(options != null) {
            for(int i = 0; i < options.length; i++) {

out.write("\r\n");
out.write("				<tr>\r\n");
out.write("					<th>옵션 ");
out.print( i+1 );
out.write("</th>\r\n");
out.write("					<td>");
out.print(options[i] );
out.write("</td>\r\n");
out.write("				</tr>\r\n");
out.write("			");

            }
        }

out.write("\r\n");
out.write("		</tbody>\r\n");
out.write("	</table>\r\n");