Server (Scope ; Servlet/JSP 내장 객체와 범위)

Jieun·2023년 3월 21일
0

📝 Server 중 EL, 내장객체, JSTL 수업
#230321

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

1. page

현재 페이지만
현재 Servlet 또는 JSP에서만 사용 가능 (1페이지)
PageContext 추상클래스 이용

// jsp파일에서 작성 

<%
pageContext.setAttribute("pageMsg","페이지 범위 입니다.");
    		
pageContext.setAttribute("str", "page scope");
    			
%>
page scope pageMSg : ${pageMsg}
// 결과값은 아래 사진 참고

2. request

요청받은 페이지(Servlet/JSP)와 요청을 위임받은 페이지(Servlet/JSP)에서 사용 가능
(최소 2페이지 이상)

// java파일
req.setAttribute("message","request scope에 저장된 메세지 입니다.");
-----------------------------------------------------------------
// jsp파일 
request scope message :${message}

3. session

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

//java파일
// 1) HTTPSession 객체 얻어오기
HttpSession session = req.getSession();

// 2) session scope로 값 세팅하기
session.setAttribute("sessionValue", "999");
--------------------------------------------------
//jsp파일
session scope sessionValue : ${sessionValue}

4. application

하나의 웹 애플리케이션 당 1개만 생성되는 객체

서버 시작시 생성되며, 종료 시 까지 유지
누구든지 사용 가능


//java파일
// 1) ServletContext 객체 얻어오기
ServletContext application = req.getServletContext();
		
// 2) application 범위로 값  세팅
application.setAttribute("appValue", "애플리케이션 범위 값");
-----------------------------------------------------------------
//jsp파일
application scope appValue : ${appValue}

위 예시 결과값


🏷️ 내장객체의 우선순위

setAttribute("key", value)로 내장 객체가 세팅할 때
key 값이 중복되는 경우 범위가 작은 내장 객체가 높은 우선 순위를 갖게 된다.

${key} 로 작성.

1. page > 2. request > 3. session > 4. application


//java 파일

// page -> JSP에서 작성함
req.setAttribute("str", "request scope");
session.setAttribute("str", "session scope");
application.setAttribute("str", "application scope");
		
dispatcher.forward(req, resp);
--------------------------------------------------------------------------
//jsp파일 

//page
pageContext.setAttribute("str", "page scope");
---------------------------------------------------------------------------

우선 순위 확인 : ${str}  
// page, request, session, application key값이 모두 str로 설정
//  위에서 말한 key값이 중복되기 때문에, 우선순위 중 1순위인 pageScope가 나옴


// 위와 같이 그냥 str부르면 우선순위로 내려가니까 
// 직접적으로 가져오라고 각 value값 .key값(str) 로 값을 줌.   

  // 그래서 ${pageScope.str} 과 $[str}의 결과값이 같다.
  
page의 str 값 : ${pageScope.str}
    
request의 str 값 : ${requestScope.str}
    
session의 str 값 : ${sessionScope.str}
    
application의 str 값 : ${applicationScope.str}

위 예시 결과값

profile
👩‍💼👩‍💼➡️➡️➡️👩‍💻👩‍💻 생산자의 삶을 살기 위해 개발공부중

0개의 댓글