1. ServletContext의 역할
- 웹 애플리케이션 전역 정보 제공:
- 웹 애플리케이션의 설정 정보 (초기화 파라미터, web.xml)
- 웹 애플리케이션의 리소스 (파일, 디렉토리) 경로
- 서블릿 컨테이너(웹 서버) 정보
- 웹 애플리케이션의 컨텍스트 경로 (Context Path)
- 로그 기록
- 웹 애플리케이션 범위의 속성(Attribute) 관리:
- setAttribute(), getAttribute(), removeAttribute() 메서드를 사용하여 데이터를 저장하고 공유할 수 있다.
- 저장된 속성은 웹 애플리케이션 전체에서 접근 가능. (모든 서블릿, JSP)
- application 내장 객체(JSP)가 바로 이 ServletContext 객체.
- 요청 디스패처 (Request Dispatcher) 획득:
- getRequestDispatcher() 메서드를 사용하여, 다른 서블릿이나 JSP로 요청을 전달(forward())하거나 포함(include())할 수 있다.
- MIME 타입 매핑:
- 파일 확장자에 따른 MIME 타입 정보를 얻을 수 있다.
2. ServletContext 객체 얻는 방법
ServletContext 객체는 다음 방법으로 얻을 수 있습니다.
- ServletConfig 객체에서: (서블릿 초기화 시)
-
public class MyServlet extends HttpServlet { private ServletContext context; @Override public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); } // ... }
- Java
- HttpServletRequest 객체에서: (요청 처리 시)
-
Java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = request.getServletContext(); // ... }
- HttpSession 객체에서:
-
Java
HttpSession session = request.getSession(); ServletContext context = session.getServletContext();
- JSP에서는 application 내장 객체 사용:
-
Java
<% ServletContext context = application; // application은 ServletContext 타입 String serverInfo = application.getServerInfo(); %>
3. ServletContext의 주요 메서드
메서드반환 타입설명
getAttribute(String name) | Object | 지정된 이름(name)의 속성 값을 반환합니다. 없으면 null을 반환. |
getAttributeNames() | Enumeration<String> | ServletContext 객체에 저장된 모든 속성의 이름들을 Enumeration 형태로 반환. |
setAttribute(String name, Object value) | void | ServletContext 객체에 속성(attribute)을 추가합니다. 지정된 이름(name)으로 값(value)을 저장합니다. 웹 애플리케이션 전체에서 공유됨. |
removeAttribute(String name) | void | 지정된 이름(name)의 속성을 제거. |
getContextPath() | String | 웹 애플리케이션의 컨텍스트 경로(context path)를 반환. (예: /myapp) |
getInitParameter(String name) | String | web.xml에 설정된 웹 애플리케이션 초기화 파라미터(context parameter) 중 지정된 이름(name)의 값을 반환. 없으면 null을 반환. |
getInitParameterNames() | Enumeration<String> | web.xml에 설정된 모든 웹 애플리케이션 초기화 파라미터의 이름들을 Enumeration 형태로 반환. |
getMimeType(String file) | String | 주어진 파일 이름(file)의 MIME 타입(예: "text/html", "image/jpeg")을 반환. |
getRealPath(String path) | String | 주어진 상대 경로(path)에 대한 웹 애플리케이션 내의 실제 파일 시스템 경로를 반환. (파일 업로드, 리소스 접근 등에 사용) |
getResource(String path) | URL | 웹 애플리케이션 내의 주어진 상대 경로(path)에 대한 URL 객체 반환. (파일 업로드, 리소스 접근 등에 사용) 없을 경우 null |
getResourceAsStream(String path) | InputStream | 웹 애플리케이션 내의 주어진 상대 경로(path)에 대한 입력 스트림 반환 |
getRequestDispatcher(String path) | RequestDispatcher | 지정된 경로(path)에 대한 RequestDispatcher 객체를 반환. (요청 전달 및 포함에 사용) |
getServerInfo() | String | 웹 애플리케이션이 실행 중인 서버(서블릿 컨테이너)의 이름과 버전 정보를 반환. (예: "Apache Tomcat/9.0.951") |
log(String msg) | void | 웹 애플리케이션의 로그 파일에 메시지(msg)를 기록. |
log(String message, Throwable throwable) | void | 웹 애플리케이션의 로그 파일에 주어진 예외(throwable)와 관련된 메시지(message)를 기록 |
4. 사용 예시
- 웹 애플리케이션 초기화 파라미터 읽기 (web.xml):
Java
// 서블릿에서 ServletContext context = getServletContext(); String adminEmail = context.getInitParameter("adminEmail"); // "admin@example.com" String dbURL = context.getInitParameter("databaseURL"); // "jdbc:mysql://localhost:3306/mydb" // JSP에서 String adminEmail = application.getInitParameter("adminEmail");
-
XML
<web-app> <context-param> <param-name>adminEmail</param-name> <param-value>admin@example.com</param-value> </context-param> <context-param> <param-name>databaseURL</param-name> <param-value>jdbc:mysql://localhost:3306/mydb</param-value> </context-param> </web-app>
- 애플리케이션 범위 속성 설정 및 가져오기:
-
Java
// 서블릿에서 ServletContext context = getServletContext(); context.setAttribute("appVersion", "1.0"); // 애플리케이션 버전 저장 String version = (String) context.getAttribute("appVersion"); // 다른 서블릿/JSP에서 접근 //JSP에서 String version = (String) application.getAttribute("appVersion");
- 로그 기록:
-
Java
ServletContext context = getServletContext(); context.log("사용자가 로그인했습니다.");
- RequestDispatcher 가져오기
-
Java
RequestDispatcher dispatcher = context.getRequestDispatcher("/WEB-INF/views/result.jsp");
5. ServletContext vs. ServletConfig vs HttpSession
객체범위용도생성 시점
ServletContext | 웹 애플리케이션 전체 | 애플리케이션 전체 설정, 공유 데이터, 리소스 접근, 로그 | 웹 애플리케이션 시작 시 (한 번) |
ServletConfig | 개별 서블릿 | 서블릿 초기화 파라미터, 서블릿 이름 | 서블릿 객체 생성 시 (서블릿 당 한 번) |
HttpSession | 클라이언트 세션 | 사용자별 데이터 (로그인 정보, 장바구니 등) | 클라이언트 첫 요청 시 (사용자별) |
'개발 > servlet' 카테고리의 다른 글
HttpSession 과 Cookie 인터페이스 정리 (0) | 2025.03.05 |
---|---|
ServletConfig 인터페이스 정리 (0) | 2025.03.05 |
Servlet RequestDispatcher 정리 (0) | 2025.03.05 |
Servlet Request 객체와 Response의 주요 메서드 (0) | 2025.03.05 |
Servlet은 어떤식으로 작동할까? (0) | 2025.03.05 |