05_Scope

김정욱·2023년 3월 22일
0

Server 복습

목록 보기
8/13
post-thumbnail

Servlet/JSP 내장 객체와 범위(scope)

✔️ Servlet/JSP에는 기본적으로 내장되어있는 4가지 객체가 존재함

✔️ 4종류의 객체는 각각 영향을 미칠 수 있는 범위가 다르다

1. page : 현재 페이지
-> 현재 Servlet 또는 JSP에서만 사용 가능 (1페이지)

2. request : 요청받은 페이지(Servlet/JSP)와 
			 요청을 위임받은 페이지(Servlet/JSP)에서 사용 가능

3. session : 현재 사이트에 접속한 브라우저당 1개씩 생성.
			 브라우저가 종료되거나, session이 만료될 때 까지 유지
(세션에 로그인 정보를 기록해둠 
-> 브라우저가 종료되거나 로그아웃 되기 전까지 계속 로그인 상태 유지됨)

4. application : 하나의 웹 애플리케이션 당 1개만 생성되는 객체
	-> 서버 시작 시 생성되며 종료 시 까지 유지
	-> 누구든지 사용 가능


💡 내장 객체의 우선 순위
✔️ setAttribute("key", value)로 내장 객체가 값을 세팅할 때 key 값이 중복되는 경우
${key}로 작성하는 경우 범위가 작은 내장 객체가 높은 우선 순위를 가진다
page > request > session > application

1) index.html

<ul>
  <li>
    <a href="scope">2. Servlet/JSP 내장 객체와 범위(scope)</a>
    <!-- 상대 경로 방식 -->
  </li>
</ul>  
<!-- 경로 방식이란? -->
<!-- 절대 경로 방식 : 프로젝트부터 요청 서비스 주소까지 작성 -->
<!-- 
상대 경로 방식 : 폴더 구조처럼 생각. 형제 요소는 이름만 부르면 접근 가능
현재 페이지 주소 : /JSPProject2/index.html
목표 페이지 주소 : /JSPProject2/scope
-->

2) servlet

@WebServlet("/scope")
public class ScopeServlet extends HttpServlet{
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws ServletException, IOException {

	RequestDispatcher dispatcher = 
    req.getRequestDispatcher("/WEB-INF/views/el/scope.jsp");

	// 1. page : JSP에서만 사용 가능
    // PageContext 추상클래스 이용

    // 2. request
    req.setAttribute("message", "request scope에 저장된 메시지 입니다");

    // 3. session
    // 1) HttpSession 객체 얻어오기
	HttpSession session = req.getSession();

    // 2) session scope로 값 세팅하기
	// * page, request, session, applicaton은 모두 사용법이 동일
	session.setAttribute("sessionValue", "999");

    // 4. application
    // 1) SevletContext 객체 얻어오기
	ServletContext application = req.getServletContext();

    // 2) application 범위로 값 세팅
	application.setAttribute("appValue", "애플리케이션 범위 값");

	// 내장 객체 우선 순위 확인
	req.setAttribute("str", "request scope");
	session.setAttribute("str", "session scope");
	application.setAttribute("str", "application scope");

	dispatcher.forward(req, resp);
  }  
}

3) JSP

💡 상단에 작성!!
<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8" %>

----------------------------- 생략 -----------------------------
<ul>
  <li>
    <% pageContext.setAttribute("pageMsg", "페이지 범위 입니다");
       pageContext.setAttribute("str", "page scope"); %>

    page scope pageMsg : ${pageMsg}
    </li>

    <li>request scope message : ${message}</li>

    <li>session scope sessionValue : ${sessionValue}</li>

    <li>application scope appValue : ${appValue}</li>
</ul>

<<hr>

<h1>우선 순위 확인 : ${str}</h1>

<h3>page의 str 값 : ${pageScope.str}</h3>

<h3>request의 str 값 : ${requestScope.str}</h3>

<h3>session의 str 값 : ${sessionScope.str}</h3>

<h3>application의 str 값 : ${applicationScope.str}</h3>

profile
절박한 마음을 갖고 하루를 보내자!!

0개의 댓글