1. Scope
(1) 정리
(2) 종류
Scope 종류 | 정리 | Example |
Application Scope | 애플리케이션이 생성 -> 소멸될 때까지 유지되는 Scope | |
Session Scope |
세션 객체가 생성되서 소멸될 때 까지 유지되는 Scope. 상태 유지하기 위해 사용하는 scope |
Request Scope 에서는 하나의 요청이 들어와서 끝날 때까지만 유지된다면 Session Scope은 여러 개의 요청이 와도 세션 객체가 유지되는 한 계속 유지된다. |
Request Scope | 클라이언트로부터 요청이 들어와서 서버가 응답을 보낼 때까지 사용할 수 있는 scope | Forward 에서 서블릿 1 -> 서블릿 2로 갈때 Request 영역은 동일했는데, 이것도 request scope에 속한다. |
Page Scope | Servlet이나 JSP 그 한 페이지 내에서만 사용할 수 있는 변수 | Forward가 되면 특정 페이지의 page scope에 지정된 변수는 사용할 수 없다. |
2. Page Scope
(1) 정리: 서블릿이든 JSP든 딱 그 페이지 내에서만 유지되는 scope
(2) 특징
* PageContext 추상 클래스를 사용한다.
* JSP 페이지에서 따로 정의할 필요 없이 pageContext라는 내장 객체(JSP -> Servlet으로 자동 변환 시 생기는 내부 객체로, JSP 안에서 따로 선언하지 않아도 사용 가능)로 사용가능하다.
* forward될 경우 Page scope에 지정된 변수는 사용 불가하다.
* 사용방법은 나머지 scope와 동일하다.
* 지역변수처럼 사용된다.
* JSP에서 값을 저장한 후 해당 값을 EL, JSTL 에서 사용할 때 사용된다.
* 사용시 setAttribute, getAttribute로 값을 설정하고 가져온다.
(3) 사용 예
JSP 내에서
pageContext.setAttribute("name", value);
pageContext.getAttribute("name");
3. Request Scope
(1) 정리: WAS가 http 요청을 받아서 클라이언트에게 응답할 때까지 값을 유지하고자 할 때 사용
(2) 특징
* HttpServletRequest 객체를 사용한다.
* 응답이 끝나면 사라진다.
* 다른 scope에서와 같이 setAttribute, getAttribute() 메서드를 사용한다.
* forward할 때 값을 유지하고자 사용한다.
(3) 사용 예
Forward 할 때
처음의 서블릿에서 다음과 같이 HttpServletRequest 객체에 값을 저장(setAttribute() 사용)하여 보낸다.
protected void service(HttpServletRequest request, HttpServletResponse response) {
int diceValue = (int)(Math.random() * 6) + 1;
request.setAttribute("dice", diceValue);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/next");
requestDispatcher.forward(request, response);
}
다음 서블릿에서는 getAttirbute() 메서드로 HttpServletRequest 객체에 저장된 값을 받아온다.
protected void service(HttpServletRequest request, HttpServletResponse response) {
int dice = (Integer)response.getAttribute("dice");
}
3. Session Scope
(1) 정리: 웹 브라우저별(각 클라이언트)로 변수를 관리하고자할 경우 사용. 지정된 시간동안, 또는 브라우저를 닫을 때까지 유지된다.
(2) 특징
* 웹 브라우저 간 탭 간에는 같은 세션 정보가 공유된다.
* 세션과 세션 scope는 장바구니처럼 사용자별로 유지되어야 할 정보가 있을 때 사용한다.
* HttpSession 인터페이스를 구현한 객체를 사용한다. 내장객체(JSP -> Servlet 변환시 자동으로 생성되는 객체) 중
javax.servlet.http.HttpSession session = null;
로 정의되어있다.
* 따라서 JSP에서는 session이라는 내장변수로 정의하지않고 바로 사용할 수 있다.
* 서빌릿에서는 HttpServletRequest의 getSession() 메서드를 사용하여 session 객체를 얻는다.
* 다른 scope에서와 같이 setAttribute, getAttribute() 메서드를 사용한다.
4. Application Scope
(1) 정리: 서버에는 여러 개의 웹 앱이 존재할 수 있는데, 각 웹 앱별로 유지해야할 데이터를 관리하는 scope으로서, 웹 앱이 시작된 이후부터 종료될 때까지 유지되는 변수
(2) 특징
* 여러 다른 클라이언트가 접속할지라도 같은 웹 앱에 접속하는 경우에는 해당 웹 앱의 application scope가 유지되고, application scope에 있는 객체에 모든 클라이언트가 접근 가능하다.
* ServletContext 인터페이스를 구현한 객체를 사용한다.
* JSP에서는 application이라는 내장 객체를 이용한다.
* servlet에서는 getServletContext() 메서드를 이용하여 application 객체를 생성한다.
* 웹 앱 한 개당 단 한 개의 application 객체가 사용될 수 있다.
* 다른 scope에서와 같이 객체에 접근할 때는 setAttribute, getAttribute() 메서드를 사용한다.
(3) 실습
ApplicationScope01.java 라는 서블릿 1에서 ServletContext 객체, 즉 application scope에 속하는 객체를 하나 생성하고 value라는 이름으로 1을 저장하여 초기화하고 현재 value값을 표시해준다.
ApplicationScope02.java라는 서블릿 2에서는 그 객체에 1을 더하고 화면에 value값을 표시해준다.
v라는 JSP 파일에서는 그 객체에 2를 더한다.
ApplicationScope01.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ServletContext application = getServletContext();
int value = 1;
application.setAttribute("value", value);
out.println("<h1>value: " + value + "</h1>");
}
ApplicationScope02.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
try {
ServletContext application = getServletContext();
int value = (Integer)application.getAttribute("value");
value ++;
application.setAttribute("value", value);
out.println("<h2>value: " + value + "</h2>");
}
catch (NullPointerExcption e) {
System.out.println("value값 설정이 안되어있습니다.");
}
}
applicationscope01.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>
<%
try {
int value = (Integer)application.getAttribute("value");
value = value + 2;
application.setAttribute("value", value);
} catch (NullPointerException e) {
%>
<h1>설정한 값이 없습니다.</h1>
<%
}
%>
</body>
</html>
여기서 만약
JSP 먼저 실행하면: 값이 정해지지 않았다고 나온다.
서블릿 1 -> JSP -> 서블릿 2 실행하면: 3이 나올 것이다.
서블릿 1 -> JSP -> 서블릿 2 -> 서블릿 1 실행하면: 1이 나올 것이다.
웹 앱을 종료하지 않고 다른 브라우저에서 사용하면 계속 value값이 이어져 사용될 것이다.