• Home
  • About
    • Jiwon Jeong photo

      Jiwon Jeong

      끊임없이 배우며 성장하는 엔지니어

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

Scope

20 Apr 2021

Reading time ~1 minute

Scope

  1. Application : 웹 어플리케이션이 시작되고 종료될 때까지 변수가 유지되는 경우 사용 (실습에서 했었던 firstweb,exam 등과 같은 프로젝트 하나가 웹 어플리케이션 )
  2. Session : 웹 브라우저 별로 변수가 관리되는 경우 사용 (클라이언트마다 하나씩 가지고 있음)
  3. Request : http요청을 WAS가 받아서 웹 브라우저에게 응답할 때까지 변수가 유지되는 경우 사용
  4. Page : 페이지 내에서 지역변수처럼 사용

e.g) Forward 에서 서로다른 Servlet 2개(Page는 다름) but 같은 request 객체 공유 (Page < Request)

  • 출처 : https://mobiyujin.tistory.com/26

Application Scope

  1. ApplicationScope01, ApplicationScope02 서블릿 2개 생성
  2. applicationscope01.jsp 생성
  3. ApplicationScope01 서블릿에서는 Application scope로 “value”에 1이라는 값 저장
  4. ApplicationScope02 서블릿은 Application scope로 저장된 “value” 값에 1을 더한 후 그 결과 출력
  5. applicationscope01.jsp는 Application Scope로 저장된 “value” 값에 2을 더한 후 그 결과 출력

ApplicationScope01.java

    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);
        
        
        out.println("<h1>value : " + value + "</h1>");
        
    }

ApplicationScope02.java

    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.println("<h1>value : " + value + "</h1>");
        }catch(NullPointerException ex) {
            out.println("value가 설정되지 않습니다.");
        }
    }

ApplicationScope01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    try{
        int value = (int)application.getAttribute("value");
        value = value + 2;
        application.setAttribute("value", value);
%>
        <h1><%=value %></h1>
<%        
    }catch(NullPointerException ex){
%>
        <h1>설정된 값이 없습니다.</h1>
<%        
    }
%>

</body>
</html>

결과화면

Application Scope는 웹 어플리케이션을 사용하는 모든 브라우저에서 같은 값을 사용한다.



WebProgrammingservletjsptomcat Share Tweet +1