본문 바로가기

자바 웹/서블릿

load-on-startup 기능

728x90

 서블릿은 브라우저에 최초 요청 시 init() 메서드를 실행한 후 메모리에 로드되어 기능을 수행하기 때문에 최초 요청에 대해서는 실행 시간이 길어진다.

 이런 단점을 보완하기 위해서 사용하는 기능이 load-on-startup이다.

  • 톰캣 컨테이너가 실행되면서 미리 서블릿을 실행
  • 지정한 숫자가 0보다 크면 톰캣 컨테이너가 실행되면서 서블릿이 초기화
  • 지정한 숫자는 우선순위를 의미하며, 작은 숫자부터 먼저 초기화

이 기능을 구현하는 방법으로는 애너테이션을 이용하는 방법과 web.xml에 설정하는 방법이 있다.

 

애너테이션을 이용하는 방법

애너테이션을 이용해 web.xml에서 공통 메뉴를 읽어오기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//애너테이션으로 설정한 매개변수에 loadOnStartup 속성을 추가하고 우선순위를 1로 설정
@WebServlet(name = "loadConfig", urlPatterns = { "/loadConfig" }, loadOnStartup = 1)
public class LoadAppConfig extends HttpServlet {
    
    //변수 context를 멤버 변수로 선언
    private ServletContext context;
    
    public void init(ServletConfig config) throws ServletException {
        System.out.println("LoadAppConfig의 init 메서드 호출");
        //init메서드에서 ServletContext객체를 얻음
        context = config.getServletContext();
        
        //getInitParameter메서드로 web.xml의 메뉴 정보를 읽어옴(이전에 만들었던 내용을 가져오는 것)
        String menu_member = context.getInitParameter("menu_member");
        String menu_order = context.getInitParameter("menu_order");
        String menu_goods = context.getInitParameter("menu_goods");
        
        //가져온 메뉴 정보를 ServletContext객체에 바인딩
        context.setAttribute("menu_member", menu_member);
        context.setAttribute("menu_order", menu_order);
        context.setAttribute("menu_goods", menu_goods);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getParameter("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        //브라우저에서 요청 시 ServletContext 객체의 바인딩 된 메뉴 항목을 가져옴
        String menu_member = (String) context.getAttribute("menu_member");
        String menu_order = (String) context.getAttribute("menu_order");
        String menu_goods = (String) context.getAttribute("menu_goods");
        
        out.print("<html><body>");
        out.print("<table border=1 cellspacing=0><tr>메뉴 이름</tr>");
        out.print("<tr><td>"+menu_member+"</td></tr>");
        out.print("<tr><td>"+menu_order+"</td></tr>");
        out.print("<tr><td>"+menu_goods+"</td></tr>");
        out.print("</table></html></body>");
    }
}
 
cs

 

web.xml에서 <context-param>태그 안에 있는 정보를 가져오는 것

 

결과

 

web.xml에 설정하는 방법

 

 

728x90

'자바 웹 > 서블릿' 카테고리의 다른 글

서블릿 필터와 리스너 기능  (0) 2022.05.12
쿠키와 세션  (0) 2022.05.08
바인딩  (0) 2022.04.11
서블릿 비즈니스 로직 처리  (0) 2022.03.27
서블릿 기초  (0) 2022.03.22