ServletContext

moon.kick·2025년 4월 15일
0

아주 잘 정리하셨어요! 이 내용을 조금 더 체계적으로 정리해서 ServletContext (application 객체) 의 역할과 주요 메서드를 설명드릴게요. 발표자료나 복습용으로도 바로 쓸 수 있게 구성했어요.


🌐 ServletContext (application 객체)

📌 역할

  • 웹 애플리케이션 전체에서 공유되는 전역 객체
  • 서블릿 간, JSP 간, 사용자 간 공통 데이터를 저장하고 공유할 수 있음
  • 서버가 시작될 때 생성되어, 종료될 때 소멸

🔧 주요 메서드 정리

메서드설명예시
setAttribute(String name, Object value)이름(name)으로 객체를 저장application.setAttribute("count", 10);
getAttribute(String name)저장된 객체를 이름으로 조회Integer c = (Integer)application.getAttribute("count");
removeAttribute(String name)지정한 이름의 객체를 제거application.removeAttribute("count");
getAttributeNames()저장된 모든 속성 이름을 나열Enumeration e = application.getAttributeNames();
getRealPath(String path)웹 루트 기준 실제 파일 경로 반환String realPath = application.getRealPath("/images/logo.png");

📁 ServletContext vs HttpSession vs Request

객체범위생명주기예시
application (ServletContext)웹 앱 전체서버 시작 ~ 종료방문자 수, 공통 설정값
session사용자 별브라우저 종료/타임아웃로그인 정보, 장바구니
request요청 1회요청 ~ 응답폼 입력값, 검색 조건

✅ 사용 예시 (JSP에서)

<%
application.setAttribute("siteName", "내 JSP 사이트");
String name = (String)application.getAttribute("siteName");
out.print("사이트 이름: " + name);
%>

필요하다면 ServletContext를 서블릿에서 사용하는 예제 코드도 드릴 수 있어요. 예를 들어 init()에서 공통 변수 설정하거나, 모든 서블릿이 공유하는 데이터를 저장할 때 유용하죠! 더 확장해볼까?

profile
@mgkick

0개의 댓글