JSP 데이터 저장소
서블릿과 마찬가지로 jsp도 데이터를 다른 리소스로 보낼 경우가 생긴다.
사실 jsp만으로 코드를 짜는 일은 많지 않아서 서블릿과 엄격히 분리하는건 괜한 일 같긴하다.
하지만 어떤건 서블릿과 공유되고 어떤건 공유되지 않는지 알아야 사용을 수월하게 할 수 있다고 생각한다.
jsp에서 데이터를 저장할 수 있는 객체는 총 4개가 존재한다.
|
이름 |
용도 + 데이터 사용 범위 |
라이프 사이클 |
|
pageContext |
|
|
|
request |
|
|
|
session |
|
|
|
application |
|
|
pageContext
해당 페이지 내에서만 사용할 수 있는 객체다.
다른 페이지넘어가면 해당 페이지에서 저장한 데이터는 사용할 수 없다.
그래서 데이터 저장 용도로는 실질적으로 활용도가 낮고 잘 쓰이진 않는다.
아래 코드는 pageContext를 이용해 데이터를 저장하고 로드하는 코드다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
String pc1 = "페이지 컨텍스트 저장";
String pc2 = "";
%>
<%
pageContext.setAttribute("pc1", pc1);
String pc2 = (String) pageContext.getAttribute("pc1");
%>
<%= pc2 %>
</body>
</html>
결과물은 아래와 같다.

reqrest
request는 서블릿에서의 request와 동일하게 사용한다.
데이터는 request 흐름상에 있는 곳에서만 사용이 가능하다.
첫번째 jsp 파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
String rq = "리퀘스트에 저장";
%>
<%
request.setAttribute("rq", rq);
%>
<%
pageContext.forward("NewFile2.jsp");
%>
</body>
</html>
2번째 jsp 파일
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 2번째 jsp 파일 </h1>
<%= request.getAttribute("rq") %>
</body>
</html>
결과는 아래와 같이 2번째 페이지로 request가 넘어갔고 거기서 데이터를 꺼내서 인쇄를 한 모습이다.

session, application
둘 다 서블릿의 session, servletContext와 같다.
request 흐름 없이도 어느 jsp파일에서든 데이터를 저장 로드할 수 있다.
session, application에 데이터를 저장하는 첫번째 jsp 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
String se = "세션에 저장";
String ap = "어플리케이션에 저장";
%>
<%
session.setAttribute("se", se);
application.setAttribute("ap", ap);
%>
</body>
</html>
session, application에서 데이터를 로드하는 두번째 jsp 코드
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 2번째 jsp 파일 </h1>
<%=
session.getAttribute("se")
%>
<br>
<%=
application.getAttribute("ap")
%>
</body>
</html>
결과물은 아래와 같다. 별다른 처리 없이 저장만 하면 어느 jsp파일에서든 로드가 가능하다.
