이번 실습에서는 주석, include 지시어, 각종 스크립트 요소들의 활용을 다룬다.

실습을 통해 JSP 스트립트 요소들의 특징을 이해하고 활용할 수 있다.

실습 내용

프로젝트의 WebContent -> basic 폴더에 basicTotal.jsp 파일을 생성한다.

기본 코드는 다음과 같이 작성 한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>JSP Basic Examples</title>
</head>
<body>
	<h2>JSP Basic Examples</h2>
	<hr>
...
</body>
</html>

JSP는 특성상 HTML, Java, JSP 주석을 모두 사용할 수 있다. JSP 주석은 컴파일 과정에서 처리 되므로 클라이언트로 전달된 html 소스에서 보이지 않는다.

<H3>1. comment <!-- JSP comment: this text will not shown in browser --> </H3>

JSP에서 메서드나 멤버변수의 선언은 <%! %>을 사용한다. 여기서는 배열, 숫자 변수와 메서드를 선언한 다음 스크립트 요소를 통해 참조 한다.

<%!
	String[] members = {"James", "Martin", "Kim", "Hong"};
	int num1 = 10;
	int calc(int num2) {
		return num1+num2;
	}
%>

메서드 호출과 결과 출력은 다음과 같다.

<h3>2. calc(10) method result: <%=calc(10) %></h3>

다른 jsp 파일을 현재 jsp 에 포함 한다. 화면 구성요소를 분리하고 재활용 가능한 기법이다.

<h3>3. include: hello.jsp</h3>
<%@include file="hello.jsp" %>
<hr>

앞에서 선언한 members 배열을 스크립트릿을 이용해 본문에서 활용하는 코드 이다. 모든 코드를 스크립트릿에서 처리하게 되면 out.println()을 이용해 html 코드를 출력해야 하므로 중간에 스크립트릿을 닫고 html 로 출력한 다음 for 문을 닫는 구조를 사용 했다.

<h3>4. print all members</h3>
	<ul>
	<%
		for(String name : members) {
	%>
		<li><%=name %></li>
	<% } %>
	</ul>

실행 결과는 다음과 같다.

서블릿 생성

예제의 전체 코드는 다음과 같다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Basic Examples</title>
</head>
<body>
	<h2>JSP Basic Examples</h2>
	<hr>

	<%!String[] members = { "James", "Martin", "Kim", "Hong" };
	int num1 = 10;

	int calc(int num2) {
		return num1 + num2;
	}%>

	<H3>
		1. comment
		<!-- JSP comment: this text will not shown in browser -->
	</H3>
	<h3>
		2. calc(10) method result:
		<%=calc(10)%></h3>
	<hr>
	<h3>3. include: hello.jsp</h3>
	<%@include file="hello.jsp"%>
	<hr>
	<h3>4. print all members</h3>
	<ul>
		<%
			for (String name : members) {
		%>
		<li><%=name%></li>
		<%
			}
		%>
	</ul>
</body>
</html>