ServletContext의 핵심 활용법

웹 애플리케이션이 구동될 때, 서블릿 컨테이너는 각 웹 앱마다 고유한 ServletContext 인스턴스를 생성한다. 이 객체는 해당 웹 애플리케이션 전체의 맥락을 담당하며, 여러 서블릿 간에 정보를 공유하는 중추적인 역할을 수행한다.

1. 애플리케이션 범위 데이터 공유

서로 다른 서블릿에서도 동일한 ServletContext를 통해 데이터를 주고받을 수 있다. 아래 예시는 데이터를 저장하는 서블릿과 이를 조회하는 서블릿을 각각 구현한 것이다.

데이터 저장: StoreServlet

public class StoreServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        ServletContext ctx = getServletContext();
        String nickname = "DevYoon";
        ctx.setAttribute("nickname", nickname);
    }
}

데이터 조회: FetchServlet

public class FetchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        ServletContext ctx = getServletContext();
        String value = (String) ctx.getAttribute("nickname");
        
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("조회 결과: " + value);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

2. 웹 플리케이션 초기화 파라미터 접근

web.xml에 정의된 컨텍스트 초기화 파라미터는 ServletContext를 통해 코드에서 참조할 수 있다.
<context-param>
    <param-name>dbConnectionString</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    
    ServletContext ctx = getServletContext();
    String dbUrl = ctx.getInitParameter("dbConnectionString");
    
    resp.getWriter().print("데이터베이스 접속 정보: " + dbUrl);
}

3. 요청 포워딩 처리

클라이언트를 거치지 않고 서버 내부에서 다른 자원으로 요청을 전달할 수 있다. 이는 URL이 변경되지 않는 특징이 있다.
public class ForwardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        ServletContext ctx = getServletContext();
        // "/target" 경로의 서블릿으로 내부 전달
        ctx.getRequestDispatcher("/target").forward(req, resp);
    }
}

포워딩 vs 리다이렉트

구분 포워딩 (Forward) 리다이렉트 (Redirect)
처리 방식 서버 내부 이동 클라이언트 재요청
URL 변화 변경 없음 변경됨
요청 횟수 1회 2회

4. 애플리케이션 내 자원 파일 읽기

ServletContextgetResourceAsStream() 메서드를 제공하여, 클래스패스 기준의 리소스 파일을 스트림 형태로 로드할 수 있다. 주로 Properties 파일이나 정적 설정 파일을 읽을 때 활용된다.
public class ResourceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        ServletContext ctx = getServletContext();
        InputStream is = ctx.getResourceAsStream("/WEB-INF/config/app.properties");
        
        Properties props = new Properties();
        props.load(is);
        
        String appName = props.getProperty("application.name");
        resp.getWriter().print("애플리케이션명: " + appName);
    }
}

태그: Servlet ServletContext Java EE HTTP Request Forwarding Web Application

6월 10일 22:56에 게시됨