JSP 내장 객체와 액션 태그2 (D-95)

최우정·2022년 5월 17일
0

100일

목록 보기
6/17
post-thumbnail

📒 영역 객체와 속성

✏️ 영역 객체(scope)와 속성(Attribute)

JSP에서 제공하는 내장 객체들 중 session, request, application 객체들은 해당 객체에 정의된 유효 범위 안에서 필요한 객체(데이터)들을 저장하고 읽어 들임으로써 서로 공유할 수 있는 특정한 영역을 가지고 있다.

공유되는 데이터를 속성(Attribute)이라고 하며, 속성을 공유할 수 있는 유효 범위를 영역(scope)이라고 한다.

JSP에서 정의하는 영역은 page, request, session, application 으로 구성되며 이들 영역은 각각 pageContext, request, session, application 내장 객체를 통해서 속성을 설정하거나 읽어 들일 수 있다. 특별히 pageContext 내장 객체는 page 영역 뿐만이 아니라 모든 영역의 속성에 대한 접근이 가능하다.

✏️ 속성과 관련된 메소드들

영역 객체의 속성을 설정하고 읽어 들이기 위해서 JSP는 다음과 같이 대표적인 4가지 메소드를 제공한다. 이들 4가지 메소드들은 pageContext, request, session, application 내장 객체들이 동일하게 정의하고 있는 메소드들이다.

attributeTest1_Form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Attribute Test Form</title>
</head>
<body>
<h2>영역과 속성 테스트</h2>
<form action="attributeTest1.jsp" method="post">
<table border="1">
	<tr><td colspan="2">Application 영역에 저장할 내용들</td></tr>
	<tr>
		<td>이름</td>
		<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<td>아이디</td>
		<td><input type="text" name="id"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="전송"></td>
	</tr>
</table>
</form>
</body>
</html>

attributeTest1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>영역과 속성 테스트</h2>
<%
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
String id=request.getParameter("id");
if(name!=null&&id!=null){
	application.setAttribute("name",name);
	application.setAttribute("id",id);
}
%>
<h3><%=name %>님 반갑습니다.<br><%=name %>님의 아이디는 <%=id %>입니다.</h3>
<form action="attributeTest2.jsp" method="post">
<table border="1">
	<tr><td colspan="2">Session 영역에 저장할 내용들</td></tr>
	<tr>
		<td>e-mail 주소</td>
		<td><input type="text" name="email"></td>
	</tr>
	<tr>
		<td>집 주소</td>
		<td><input type="text" name="address"></td>
	</tr>
	<tr>
		<td>전화번호</td>
		<td><input type="text" name="tel"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="전송"></td>
	</tr>
</table>
</form>
</body>
</html>

attributeTest2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>영역과 속성 테스트</h2>
<%
request.setCharacterEncoding("UTF-8");
String email=request.getParameter("email");
String address=request.getParameter("address");
String tel=request.getParameter("tel");
session.setAttribute("email",email);
session.setAttribute("address",address);
session.setAttribute("tel",tel);

String name=(String)application.getAttribute("name");
%>
<h3><%=name %>님의 정보가 모두 저장되었습니다.</h3>
<a href="attributeTest3.jsp">확인하러 가기</a>
</body>
</html>

attributeTest3.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.Enumeration"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>영역과 속성 테스트</h2>
<table border="1">
	<tr><td colspan="2">Application 영역에 저장된 내용들</td></tr>
	<tr>
		<td>이름</td>
		<td><%=application.getAttribute("name") %></td>
	</tr>
	<tr>
		<td>아이디</td>
		<td><%=application.getAttribute("id") %></td>
	</tr>
</table>
<br>
<table border="1">
	<tr><td colspan="2">Session 영역에 저장된 내용들</td></tr>
<%
Enumeration e=session.getAttributeNames();
while(e.hasMoreElements()){
	String attributeName=(String)e.nextElement();
	String attributeValue=(String)session.getAttribute(attributeName);
	%>
	<tr>
		<td><%=attributeName %></td>
		<td><%=attributeValue %></td>
	</tr>
	<%
}
%>
</table>
</body>
</html>

브라우저를 종료하면 세션 영역은 소멸되지만 애플리케이션 영역은 그대로 살아 있다.
애플리케이션 영역은 서버를 중지시키면 소멸된다.

서버를 종료한 후 다시 attributeTest3.jsp를 요청하면 다음과 같은 화면이 출력된다.

📝 page 영역과 request 영역 비교

attributeTest4.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("pageScope", "pageValue");
request.setAttribute("requestScope", "requestValue");
%>

pageValue = <%=pageContext.getAttribute("pageScope") %><br>
requestValue = <%=request.getAttribute("requestScope") %>
</body>
</html>

포워드 기능을 이용한 페이지를 다른 페이지로 변경해서 page 영역을 소멸시키고 request 영역은 유지해보자.

attributeTest5.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("pageScope", "pageValue");
request.setAttribute("requestScope", "requestValue");
%>
<jsp:forward page="attributeTest5Result.jsp"></jsp:forward>
</body>
</html>

<jsp:forward/>라는 액션 태그를 이용해서 requestTest5Result.jsp로 포워딩 하고 있다.
forward 액션 태그로 요청을 다른 페이지로 포워딩했을 경우에는 request를 공유한다.

attributeTest5Result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
pageValue = <%=pageContext.getAttribute("pageScope") %><br>
requestValue = <%=request.getAttribute("requestScope") %>
</body>
</html>

📒 액션 태그

✏️ 액션 태그의 개요

JSP 페이지에서 자바 코드 등의 스크립트 언어를 사용하지 않고도 (즉, HTML 태그 형태로) 다른 페이지의 서블릿이나 자바빈의 객체에 접근할 수 있도록 태그를 이용해 구현된 기능을 말한다.

액션 태그를 이용해 개발자는 페이지의 흐름을 제어하거나 자바빈의 속성을 읽고, 쓰며 애플릿을 사용하는 등의 다양한 기능을 활용할 수 있다.

이러한 기능들은 스크립틀릿 등의 스크립트 요소(자바 코드)를 사용하지 않기 때문에 JSP 페이지의 내부적인 프로그램 로직을 사용자로부터 감출 수가 있다.

JSP에서 제공하는 액션 태그는 다음과 같다.

  • 페이지 흐름 제어 액션 (forward/include 액션)
  • 자바빈 사용 액션 (useBean 액션)
  • 애플릿 사용 액션 (plugin 액션)

✏️ forward 액션

<jsp: forward page="이동할 페이지"/>
<jsp: forward page="이동할 페이지"></jsp:forward>

forward 액션은 pageContext 내장 객체의 forward() 메소드가 태그로 구현된 기능이다. forward 액션은 현재 페이지의 요청과 응답에 관한 처리권을 page 속성에 지정된 이동할 페이지로 영구적으로 넘기는 기능을 한다. forward 태그를 이용해 이동할 페이지에 추가적으로 파라미터를 넘겨줄 필요가 있을 때는 <jsp:param/>태그를 사용한다.

forwardTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Forward Action Test</title>
</head>
<body>
<h2>포워드 액션 테스트</h2>
<form action="forwardTest1.jsp" method="POST">
<input type="hidden" name="forwardPage" value="forwardTest2.jsp">
<table>
	<tr>
		<td>이름	</td>
		<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<td>나이	</td>
		<td><input type="text" name="age"></td>
	</tr>
	<tr>
		<td>주소	</td>
		<td><input type="text" name="address"></td>
	</tr>
	<tr><td><input type="submit" value="전송"></td></tr>
</table>
</form>
</body>
</html>

forwardTest1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8"); %>
<html>
<body>
<jsp:forward page='<%=request.getParameter("forwardPage") %>' >
	<jsp:param name="tel" value="034-1234-5678"/>
</jsp:forward>
</body>
</html>

forwardTest2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Forward Action Test</title>
</head>
<body>
<h2>포워드 된 페이지(forwardTest2.jsp)</h2>
<table>
	<tr>
		<td>이름</td>
		<td><%=request.getParameter("name") %></td>
	</tr>
	<tr>
		<td>나이</td>
		<td><%=request.getParameter("age") %></td>
	</tr>
	<tr>
		<td>주소</td>
		<td><%=request.getParameter("address") %></td>
	</tr>
	<tr>
		<td>전화번호</td>
		<td><%=request.getParameter("tel") %></td>
	</tr>
</table>
</body>
</html>

✏️ include 액션

forward 액션은 제어권을 포워딩되는 페이지로 완전히 넘기고 그 페이지의 처리가 끝나면 모든 응답을 종료시키는 방식이다. include 액션은 임시로 제어권을 include 되는 페이지로 넘겼다가 그 페이지의 처리가 끝나면 처리 결과를 원래 페이지로 되돌아오고 다시 원래의 페이지로 제어권을 반환하는 방식이다.

includeTest1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Include Action Test</title>
</head>
<body>
<h2>인클루드 액션 테스트</h2>
<jsp:include page="includeTest2.jsp">
	<jsp:param name="name" value="hongkildong"/>
</jsp:include>
</body>
</html>

includeTest2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String name=request.getParameter("name");
%>
<html>
<body>
<b><%=name%></b>
</body>
</html>

✏️ XMLElement를 생성하는 액션 태그들

JSP에서 제공하는 XML 엘리먼트 관련 액션 태그들은 JSP 내에 XML 관련 엘리먼트들을 동적으로 생성하는 역할을 한다.

xmlGenerator.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<jsp:element name="member">
<jsp:attribute name="id">
   member1
</jsp:attribute>
<jsp:body>
   홍길동
</jsp:body>
</jsp:element>

</body>
</html>

✏️ 템플릿 페이지의 작성

top.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<a href="login.jsp">Login</a> |
<a href="join.jsp">Join</a>

bottom.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<center>Since 2008</center>

left.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<center>
<a href="./template.jsp?page=newitem">신상품</a><br><br>
<a href="./template.jsp?page=bestitem">인기상품</a><br><br>
</center>

newitem.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<b>신상품 목록입니다.</b>

bestitem.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<b>인기상품 목록입니다.</b>

template.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String pagefile=request.getParameter("page");
	if (pagefile==null){pagefile="newitem";}
%>
<html>
<head>
<title>Template Test</title>
<style>
	table{
	    margin : auto;
		width : 960px;
		color : gray;
		border : 1px solid gray;
	}
</style>
</head>
<body>
<table>
	<tr>
		<td height="43" colspan=3 align=left>
			<jsp:include page="top.jsp"/>
		</td>
	</tr>
	<tr>
		<td width="15%" align=right valign=top><br>
			<jsp:include page="left.jsp"/>
		</td>
		<td colspan=2 align=center>
			<jsp:include page='<%=pagefile+".jsp" %>'/>
		</td>
	</tr>
	<tr>
		<td width="100%" height="40" colspan="3">
			<jsp:include page="bottom.jsp"/>
		</td>
	</tr>
</table>
</body>
</html>

profile
비전공자 Java, JavaScript, Html, Css, C++ 공부중

0개의 댓글