특정 값을 현재 페이지(Servlet/JSP)에서만 사용 가능
(1페이지서만 값이 유지됨)
특정 값을 요청 받은 Servlet/JSP + 요청 위임한 Serlvet/JSP에서 사용 가능
(2페이지 이상에서 값이 유지됨)
특정 값을 현재 켜져있는 브라우저가 종료되기 전까지 어디서든 사용 가능
클라이언트가 서버 접속 -> 클라이언트 접속한 브라우저 당 session 1개 생성해서 저장 -> 브라우저 종료 시까지 session 유지
특정 값을 배포한 웹 애플리케이션이 종료되기 전까지 어디서든 사용 가능
(서버가 꺼질 때까지 유지)
page
> request
> session
> application
OOOScope
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2. Servlet/JSP 내장 객체와 범위(scope)</title>
</head>
<body>
<h1>Servlet/JSP 내장 객체와 범위(scope)</h1>
<!-- a태그를 이용한 페이지 전환도 요청(GET방식)이다! -->
<a href="EL/scope">내장 객체 범위 확인하기</a>
</body>
</html>
package edu.kh.jsp.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/EL/scope")
public class ScopeServlet extends HttpServlet{
// a태그 요청은 모두 GET 방식
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/* Serlvet/JSP 내장 객체와 범위
*
* (공통) 특정 값을
*
* page : 현재 페이지(Servlet/JSP)에서만 사용 가능
*
* request : 현재 Servlet + 요청 위임한 JSP에서 사용 가능
*
* session : 현재 켜져있는 브라우저가 종료되기 전까지 어디서든 사용 가능
* (ex. 로그인)
*
* application : 배포한 웹 애플리케이션이 종료되기 전까지 어디서든 사용 가능
* (서버가 꺼질 때 까지 유지)
*
* */
// 1. page (생략) - 기존에 알고 있던 변수의 범위
// 2. request scope
req.setAttribute("message", "request scope에 저장된 메시지입니다.");
// 3. session scope
// 3-1) HttpSession 내장 객체 얻어오기
HttpSession session = req.getSession();
// 3-2) session 범위로 값 세팅(request와 방법 동일)
session.setAttribute("sessionValue", "999");
session.setAttribute("message", "session scope에 저장된 메시지입니다.");
// 4. application scope
// 4-1) ServletContext 내장 객체 얻어오기
ServletContext application = req.getServletContext();
// 4-2) application 범위로 값 세팅(request와 방법 동일)
application.setAttribute("appValue", "세미 프로젝트 파이팅!");
application.setAttribute("message", "application scope에 저장된 메시지입니다.");
// JSP로 요청 위임
String path = "/WEB-INF/views/el/scopeResult.jsp";
RequestDispatcher dispatcher = req.getRequestDispatcher(path);
dispatcher.forward(req, resp);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>내장 객체 범위 결과</title>
</head>
<body>
<% // page scope
pageContext.setAttribute("message", "page");
%>
<pre>
request 범위 message : ${ message }
session 범위 sessionValue : ${ sessionValue }
application 범위 appValue : ${ appValue }
*** scope 우선 순위 ***
page > request > session > application
** 원하는 범위(scope)의 값 얻어오기(OOOScope)
${ requestScope.message }
${ sessionScope.message }
${ applicationScope.message }
</pre>
</body>
</html>