본문 바로가기

Wanna be a Programmer/Servlet & JSP

Servlet & JSP day5 - 초기 파라미터(ServletConfig, ServletContext), Event 모델

초기 파라미터

☞ 서버단 컴포넌트(Servlet, JSP, Listener 등)이 사용하는 문자열 중 나중에 변경 될 수 있는 문자열을 web.xml에 등록해 놓고 컴포넌트에서 호출하여 사용

나중에 변경시 설정에서만 바꾸면 컴포넌트의 수정없이 변경이 가능

☞ 초기 파라미터 2가지

◎ 특정 서블릿, JSP만 사용할 수 있는 초기 파라미터

- ServletConfig 이용

Application 내 모든 컴포넌트가 사용할 수 있는 초기 파라미터

- ServletContext 이용

 

☞ javax.servlet.ServletConfig

- Servlet 객체가 일하는 데 필요한 정보를 가지고 있는 객체

- Web Container가 생성하여 Servlet의 init() 호출시 주입

- Servlet 객체 당 하나씩 생성

 

☞ ServletConfig를 이용한 초기 파라미터 처리

1. web.xml에 초기 파라미터 설정

<servlet>

<servlet-name>서블릿 객체 이름</servlet-name>

<servlet-class>서블릿 클래스 이름</servlet-class>

<init-param>

<param-name>초기 파라미터 이름</param-name>

<param-value>초기 파라미터 값</param-value>

</init-param>

</servlet>

- 초기 파라미터가 여러개인 경우 <init-param>을 반복

2. ServletConfig 객체.getInitParameter(String paramName) : paramValue

- return type  : String ParamValue

 

하나의 클래스를 통해 두개의 Servlet 객체를 사용하는 프로그램

 

 

 

 

GreetingServlet.java

 

greeting_form.html

 

web.xml

 

 

☞ javax.servlet.ServletContext

web Application이 자체 또는 일하는데 필요한 정보를 가지고 있는 객체

- Web Component는 Web Application과 관련된 정보를 조회하거나 업무를 처리할 때

   ServletContext type객체를 이용

Web Application이 시작할 때 Web Container에 의해 생성된다.

Servlet의 getServletContext()를 통해 조회

- ServletContext ctx = getServletContext();

Web Application 당 하나가 생성됨

 

☞ ServletContext를 이용한 초기 파라미터 처리

1. web.xml에 초기 파라미터 설정

<web-app>

<context-param>

<param-name>초기 파라미터 이름</param-name>

<parm-value>초기 파라미터 값</param-value>

</context-param>

- 초기 파라미터가 여러개인 경우 <context-param> 반복

2. 코드상에서 조회

ServletContext객체.getInitParameter(String paramName) : String paramValue

 

 

ContextParamServlet.java

 

web.xml

 

ContextParamServlet의 context 객체 조회 코드를 GreetingServlet.java에 적용해도 ContextParamServlet에서 조회한 결과와 같은 값이 추가적으로 더해져 출력된다. Therefore, Web Application은 web application 내에서 값을 공유하는 하나의 Servlet Context를 가진다.

 

GreetingServlet.java에 추가한 context객체 조회 코드

 

출력결과

 

 

Event 모델

☞ Event : 컴포넌트에 가해진 동작, 변화.

Event Listener

1. 컴포넌트에서 Event가 발생하는 것을 감시하는 Container

2. 발생한 Event를 처리하는 동작을 가진 객체(Listener class)

Event Handler : 발생한 Event를 처리하는 동작(메소드)

Event Source : Event가 발생한 컴포넌트

ex) 버튼을 클릭하면 안녕이라고 출력한다.

Event Source : 버튼

Event : 클릭

Event Handler : 안녕 을 출력하는 동작