관리 메뉴

Just Do it

[스프링] root-context.xml / servlet-context.xml / web.xml 역할과 차이 본문

신입 개발자가 되기 위해 공부했던 독학 자료들/자꾸 까먹는 기본 개념 모음

[스프링] root-context.xml / servlet-context.xml / web.xml 역할과 차이

Seojoo21 2022. 3. 11. 18:24

1. Web.xml

웹 어플리케이션 서버 (WAS)가 최초로 구동될 때 (보통 톰캣을 많이 쓰니까 톰캣이 최초로 구동될 때) 각종 설정을 정의한다. 

이때 파일 내에서 여러 xml파일을 인식 할 수 있도록 설정되어 있다. 쉽게 말해 root-context.xml과 servlet-context.xml과 같은 설정 파일을 어디서 가져올 것인지를 설정해주는, 설정을 위한 설정파일이라고 보면 된다. 

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
	<servlet-name>appServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

context-param 태그 내에 root-context로 모든 서블릿과 필터들이 공유함으로써 root-context.xml이 정의되었다.

또한 listener 태그로 모든 서블릿과 필터들에 공유되는 스프링 컨테이너를 생성한다. 

다시 말해 root-context에 정의되어있는 것들을 모든 서블릿과 필터가 공유할 수 있게 해준다

 

2. servlet-context.xml

MVC Model의 View와 관련된 객체를 정의한다. URL과 관련된 Controller나, 어노테이션, ViewResolver(컨트롤러에서 view 정보에 대해 설정하는 것), Interceptor, MultipartResolver 등의 설정이 이 파일에 포함된다. 

쉽게 말해 Front-End 설정 파일이라고 생각하면 된다. 

*서블릿이란? Controller 같은 클라이언트의 요청을 처리해주고, 다시 결과를 클라이언트에게 전송해주는 프로그래밍 기술

*ViewResolver란? Controller에서 view 정보와 model을 주면 알아서 그 정보를 이용해서 view 파일을 찾아 준다.

 

웹 어플리케이션에서 클라이언트의 요청을 받기 위한 컨텍스트 설정이며, 요청과 관련된 객체를 정의한다. 

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

servlet-context 파일을 보면 위처럼 주석을 볼 수 있는데, "DispatcherServlet Context: 이 서블릿의 요청 처리 인프라를 정의한다"고 해석할 수 있다. 이것은 DispactcherServlet과 관련된 설정을 하는 것임을 의미한다. 

 

3. root-context.xml

MVC Model의 Model과 관련된 객체를 정의한다. 데이터와 관련된 Service, DAO, Database 등 비즈니스 로직과 관련된 설정이 이 파일에 포함된다. 쉽게 말해 Back-End의 설정 파일이라고 생각하면 된다.

위의 자료에서 다수의 서블릿을 가지게 되는 경우 다수의 servlet-context가 root-context의 bean 정보들을 참조하는 구조가 될 수 있다. 

 

web.xml, servlet-context.xml, root-context.xml을 통해 웹 어플리케이션으로 들어오는 모든 요청에 대한 핸들링이 가능해진다.

 

 

출처:

https://nancording.tistory.com/86

https://sbarrys.tistory.com/4

https://cluster-taek.tistory.com/entry/webxml-과-servlet-contextxml-과-root-contextxml