Servlet-4

mandarinduk·2021년 3월 17일
0

Context Path

WAS(Web Application Server)에서 웹 어플리케이션을 구분하기 위한 path를 말한다.
이클립스에서는 프로젝트를 생성할 때마다 자동으로 server.xml에 입력을 한다.

서블릿 초기화: ServletConfig 클래스

  • 특정 Servlet이 생성될 때 초기에 필요한 데이터(아이디 정보, 특정경로 등)들을 초기화 하는 것을 서블릿 초기화라고 한다.
  1. 초기화 파라미터(서블릿이 생성될 때 필요한 데이터)는 web.xml에 기술한다.
    ServletConfig 클래스를 이용해서 초기화 파라미터 사용이 가능하다.
  2. 초기화 파라미터를 web.xml 대신 Servlet 파일에 직접 기술하는 방법도 있다.

1. web.xml에 초기화 파라미터 기술하기

  1. Servlet 클래스 작성
  2. web.xml에 초기화 파라미터를 입력
  3. ServletConfig의 메서드(getInitParameter())를 이용해서 데이터를 사용(접근)한다.
web.xml

  <servlet>
	<servlet-name>ServletInit</servlet-name>
	<servlet-class>com.test.ex.ServletInit</servlet-class>
	<init-param>
	  <param-name>id</param-name>
	  <param-value>test</param-value>
	</init-param>
	<init-param>
	  <param-name>pw</param-name>
	  <param-value>1234</param-value>
	</init-param>
	<init-param>
	  <param-name>local</param-name>
	  <param-value>seoul</param-value>
	</init-param>
  </servlet>
  <servlet-mapping>
	<servlet-name>ServletInit</servlet-name>
	<url-pattern>/SI</url-pattern>
  </servlet-mapping>

2. Servlet 파일에 초기화 파라미터를 직접 기술하는 방법

  1. Servlet 클래스 작성
  2. @WebInitParam에 초기화 파라미터를 작성
  3. ServletConfig의 메서드를 이용
InitServlet.java

@WebServlet(urlPatterns = {"/InitS"}, initParams = {@WebInitParam(name="id", value="test"), @WebInitParam(name="pw", value="1234"), @WebInitParam(name="local", value="seoul")})
public class InitServlet extends HttpServlet {
	...
}

ServletContext를 이용한 데이터 공유

여러 개의 Servlet에서 데이터를 공유해야 할 경우에 context parameter를 사용한다.
web.xml 파일에 데이터를 작성하면, Servlet에서 공유할 수 있다.

  1. Servlet 클래스 작성
  2. web.xml 파일에 context parameter 기술
  3. ServletContext 메서드(getServletContext())를 이용해서 데이터를 사용
web.xml

  <context-param>
	<param-name>id</param-name>
	<param-value>test</param-value>
  </context-param>
  <context-param>
	<param-name>pw</param-name>
	<param-value>1234</param-value>
  </context-param>

ServletContextListener - contextInitialized(), contextDestroy()

웹 어플리케이션을 감시하는 리스너
리스너에 해당하는 어플리케이션이 시작, 종료 시에 호출된다.
리스너를 제작하고, web.xml 리스너를 클래스 정의

contextL.java

public class ContextL implements ServletContextListener {
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("종료");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("시작");
	}
	
}
web.xml

  <listener>
	<listener-class>com.test.ex.ContextL</listener-class>
  </listener>
profile
front-end 신입 개발자

0개의 댓글