seoyoung.dev

Scope에 대하여-[Page/Request/Session/Application] 본문

WEB/JSP

Scope에 대하여-[Page/Request/Session/Application]

seo-0 2019. 10. 7. 15:31
* Scope

  • Application : 웹 어플리케이션이 시작되고 종료될 때까지 변수가 유지되는 경우 사용
  • Session : 세션객체가 만들어져서 소멸될 때까지이므로, 요청이 여러 개 들어와도 계속 남아있는 scope.(상태 유지에 사용),  웹 브라우저 별로 변수가 관리되는 경우 사용
  • Request : http요청을 WAS가 받아서 웹 브라우저에게 응답할 때까지 변수가 유지되는 경우 사용
  • Page : 페이지 내에서 지역변수처럼 사용

* application scope

- 서블릿 2개, jsp 파일 1개 생성 

- 서블릿 1 에서는 application scope 로 value 에 값 1 을 저장

- 서블릿 2 에서는 application scope 로 저장된 value 값에 1을 더한 후, 그 결과를 출력

- jsp 에서는 application scope로 저장된 value 값에 2를 더한 후, 그 결과를 출력 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		ServletContext application = getServletContext(); 

		int value =1;
		application.setAttribute("value", value);	
	}

[ 서블릿 1 ]

- application scope 객체 : getServletContext 메소드로 얻어온다. 

- scope에 상관없이 값을 맡기거나, 얻어올때는 setAttribute랑 getAttribute 사용

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		ServletContext application = getServletContext(); 
		try {
		int value =(int) application.getAttribute("value");
		value++;
		
		application.setAttribute("value", value);
		
	out.print("<h1>value"+value+"</h1>");
	} catch(NullPointerException e) {
		out.println("value 값이 설정되지 않았습니다.");
	}
}

[ 서블릿 2 ]

- 서블릿 2 가 먼저 실행될 경우, value 는 getAttribute 하면 null 값을 받기때문에 예외처리 

 

<%
try{
	int value = (int)application.getAttribute("value");
	value += 2;
	application.setAttribute("value", value);

%>
   <h1> <%=value %></h1>
<%
} catch(NullPointerException ex){	
%>

<h1> 설정된 값이 없습니다.</h1>

<%
}
%>

[ jsp 파일 ]

 

--> application scope 는 모든 클라이언트가 공통으로 사용해야 하 값들이 있을 때 사용한다. 

--> 다른 클라이언트가 요청을 해도 값을 같이 사용한다. 

--> 웹 어플리케이션이 종료될 때까지 클라이언트가 달라도 값을 같이 사용한다.