공식문서는 Dispatcher Servlet에 대해서 뭐라고 할까요?
이번글은 공식 문서에서 소개하는 DispatchServlet에 대해 정리했습니다.
정리 범위 : Context Hierarchy ~ Servlet Config
DispatcherServlet
Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows.
The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling, and more.
The following example of the Java configuration registers and initializes the DispatcherServlet, which is auto-detected by the Servlet container
Spring MVC는 다른 많은 웹 프레임워크와 마찬가지로 중앙 서블릿인 DispatcherServlet이 요청 처리를 위한 공통 알고리즘을 제공하고, 실제 작업은 구성 가능한 대리(delegate) 컴포넌트에 의해 수행되는 프론트 컨트롤러 패턴을 중심으로 설계되어 있습니다. 이 모델은 유연하며 다양한 워크플로우를 지원합니다.
DispatcherServlet은 다른 서블릿과 마찬가지로 Java 설정이나 web.xml을 사용하여 서블릿 명세에 따라 선언되고 매핑되어야 합니다. 이어서 DispatcherServlet은 스프링 설정을 사용하여 요청 매핑, 뷰 해상도, 예외 처리 등 필요한 대리 컴포넌트를 찾습니다.
다음 예제는 자바 설정을 통해 DispatcherServlet을 등록하고 초기화하는 방법을 보여주며, 이 DispatcherServlet은 서블릿 컨테이너에 의해 자동으로 감지됩니다 (자세한 내용은 Servlet Config 참조).
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
In addition to using the ServletContext API directly, you can also extend AbstractAnnotationConfigDispatcherServletInitializer and override specific methods (see the example under Context Hierarchy).
ServletContext API를 직접 사용하는 것 외에도, AbstractAnnotationConfigDispatcherServletInitializer를 확장하고 특정 메서드를 오버라이드할 수 있습니다 (Context Hierarchy에 있는 예제를 참조하세요).
For programmatic use cases, a GenericWebApplicationContext can be used as an alternative to AnnotationConfigWebApplicationContext. See the GenericWebApplicationContext javadoc for details.
The following example of web.xml configuration registers and initializes the DispatcherServlet :
다음은 web.xml 구성 예제가 DispatcherServlet을 등록하고 초기화하는 방법을 보여줍니다.
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
Spring Boot follows a different initialization sequence. Rather than hooking into the lifecycle of the Servlet container, Spring Boot uses Spring configuration to bootstrap itself and the embedded Servlet container. Filter and Servlet declarations are detected in Spring configuration and registered with the Servlet container. For more details, see the Spring Boot documentation.
Spring Boot는 다른 초기화 순서를 따릅니다. 서블릿 컨테이너의 라이프사이클에 연결하는 대신, Spring Boot는 스프링 구성을 사용하여 자신과 내장 서블릿 컨테이너를 부트스트랩합니다. 필터와 서블릿 선언은 스프링 구성에서 감지되어 서블릿 컨테이너에 등록됩니다. 자세한 내용은 Spring Boot 문서를 참조하세요.
Context Hierarchy
DispatcherServlet expects a WebApplicationContext (an extension of a plain ApplicationContext) for its own configuration. WebApplicationContext has a link to the ServletContext and the Servlet with which it is associated. It is also bound to the ServletContext such that applications can use static methods on RequestContextUtils to look up the WebApplicationContext if they need access to it.
DispatcherServlet은 자신의 구성을 위해 일반 ApplicationContext의 확장인 WebApplicationContext를 기대합니다. WebApplicationContext는 관련된 ServletContext와 Servlet에 대한 연결을 가지고 있습니다. 또한, WebApplicationContext는 ServletContext에 바인딩되어 있어, 애플리케이션이 필요할 경우 RequestContextUtils의 정적 메서드를 사용하여 WebApplicationContext를 조회할 수 있습니다.
추가 설명
DispatcherServlet은 웹 애플리케이션을 처리하는 중심 역할을 하는 서블릿입니다. 이 서블릿은 자신을 구성하기 위해 일반적인 Spring의 ApplicationContext를 확장한 WebApplicationContext를 필요로 합니다.
WebApplicationContext는 기본 ApplicationContext에 웹 환경에 특화된 기능을 추가한 것입니다.
WebApplicationContext는 웹 애플리케이션의 ServletContext(서블릿 컨테이너의 실행 환경 정보)와 연결되어 있습니다. 즉, 애플리케이션이 실행되는 환경에 대한 정보를 포함하고 있습니다. DispatcherServlet과 같이 특정 서블릿과 연관되어 동작합니다.
WebApplicationContext가 ServletContext에 바인딩되어 있기 때문에, 애플리케이션 내 다른 코드들이 RequestContextUtils 같은 도구를 사용해 언제든지 이 WebApplicationContext를 쉽게 찾아서 사용할 수 있습니다. 이는 예를 들어, 현재 요청 처리 중에 추가적인 설정 정보나 빈(bean)에 접근할 필요가 있을 때 유용합니다.
"바인딩 되어 있다"는 표현은 WebApplicationContext가 ServletContext 내부에 저장되어 있어서, 애플리케이션 내 다른 부분에서 언제든지 쉽게 접근할 수 있도록 연결되어 있다는 의미입니다.
정리하면, DispatcherServlet이 웹 관련 설정과 리소스에 접근하기 위해 특별히 설계된 컨텍스트(WebApplicationContext)를 필요로 하며, 이를 통해 웹 애플리케이션 내에서 필요한 구성 정보를 쉽게 관리하고 사용할 수 있다는 의미입니다.
For many applications, having a single WebApplicationContext is simple and suffices. It is also possible to have a context hierarchy where one root WebApplicationContext is shared across multiple DispatcherServlet (or other Servlet) instances, each with its own child WebApplicationContext configuration. See Additional Capabilities of the ApplicationContext for more on the context hierarchy feature.
많은 애플리케이션에서는 하나의 WebApplicationContext를 사용하는 것이 단순하며 충분합니다. 또한, 하나의 루트 WebApplicationContext가 여러 DispatcherServlet(또는 다른 Servlet) 인스턴스와 공유되고, 각 인스턴스는 자체 자식 WebApplicationContext 구성을 갖는 계층 구조를 가질 수도 있습니다. 계층 구조 기능에 대한 자세한 내용은 ApplicationContext의 추가 기능을 참조하세요.
The root WebApplicationContext typically contains infrastructure beans, such as data repositories and business services that need to be shared across multiple Servlet instances. Those beans are effectively inherited and can be overridden (that is, re-declared) in the Servlet-specific child WebApplicationContext, which typically contains beans local to the given Servlet. The following image shows this relationship:
루트 WebApplicationContext는 일반적으로 여러 서블릿 인스턴스 간에 공유되어야 하는 데이터 저장소 및 비즈니스 서비스와 같은 인프라 빈을 포함합니다. 이러한 빈들은 효과적으로 상속되며, 해당 서블릿에 국한된 빈을 포함하는 서블릿 전용 자식 WebApplication Context에서 재정의(즉, 재선언)될 수 있습니다. 다음 이미지는 이러한 관계를 보여줍니다.
추가 설명
부모 WebApplicationContext에 정의된 공통 인프라 빈들을 자식 WebApplicationContext가 상속받아 사용할 수 있으며, 필요한 경우 자식 컨텍스트에서 해당 빈을 재정의할 수도 있다는 의미입니다.
The following example configures a WebApplicationContext hierarchy:
다음 예제는 WebApplicationContext 계층 구조를 구성합니다:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
If an application context hierarchy is not required, applications can return all configuration through getRootConfigClasses() and null from getServletConfigClasses()
애플리케이션 컨텍스트 계층 구조가 필요하지 않은 경우, 애플리케이션은 getRootConfigClasses()를 통해 모든 구성을 반환하고, getServletConfigClasses()에서는 null을 반환할 수 있습니다.
추가 설명
getRootConfigClasses()가 반환하는 RootConfig는 루트 애플리케이션 컨텍스트를 설정합니다. 이 컨텍스트에는 여러 서블릿에서 공유되어야 하는 공통 인프라 빈들이 포함됩니다.
getServletConfigClasses()가 반환하는 App1Config는 서블릿 전용 자식 애플리케이션 컨텍스트를 설정하며, 이는 RootConfig에서 정의된 빈들을 상속받으면서 해당 서블릿에 특화된 빈들을 추가할 수 있습니다.
The following example shows the web.xml equivalent:
다음 예제는 web.xml에 해당하는 구성을 보여줍니다:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app1-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app1</servlet-name>
<url-pattern>/app1/*</url-pattern>
</servlet-mapping>
</web-app>
If an application context hierarchy is not required, applications may configure a “root” context only and leave the contextConfigLocation Servlet parameter empty.
애플리케이션 컨텍스트 계층 구조가 필요하지 않은 경우, 애플리케이션은 “root” 컨텍스트만 구성하고 contextConfigLocation 서블릿 파라미터를 비워 둘 수 있습니다.
Special Bean Types
The DispatcherServlet delegates to special beans to process requests and render the appropriate responses. By “special beans” we mean Spring-managed Object instances that implement framework contracts. Those usually come with built-in contracts, but you can customize their properties and extend or replace them.
DispatcherServlet은 요청을 처리하고 적절한 응답을 렌더링하기 위해 특수 빈들에게 위임합니다. 여기서 "특수 빈"이란 프레임워크 계약을 구현하는 스프링이 관리하는 객체 인스턴스를 의미합니다. 이들은 보통 내장된 계약을 가지고 제공되지만, 그 속성을 사용자 정의하거나 확장 또는 대체할 수 있습니다.
추가 설명
이 문장은 DispatcherServlet이 웹 요청을 직접 처리하지 않고, 스프링이 관리하는 특정 객체(빈)들에게 작업을 위임한다는 의미입니다.
The following table lists the special beans detected by the DispatcherServlet:
다음은 DispatcherServlet에 의해 감지되는 특수 빈들을 나열한 표입니다:
HandlerMapping
요청을 전처리 및 후처리를 위한 인터셉터 목록과 함께 핸들러에 매핑합니다. 이 매핑은 일부 기준에 기반하며, 그 세부 사항은 HandlerMapping 구현에 따라 다릅니다.
두 가지 주요 HandlerMapping 구현체는 RequestMappingHandlerMapping (이는 @RequestMapping 애너테이션이 붙은 메서드를 지원합니다)과 SimpleUrlHandlerMapping (이는 URI 경로 패턴을 핸들러에 명시적으로 등록합니다)입니다.
HandlerAdpater
요청에 매핑된 핸들러를, 핸들러가 실제로 어떻게 호출되든 상관없이, DispatcherServlet이 호출하도록 돕습니다. 예를 들어, 애너테이션이 붙은 컨트롤러를 호출하려면 애너테이션을 해석해야 합니다. HandlerAdapter의 주요 목적은 이러한 세부 사항으로부터 DispatcherServlet을 보호하는 것입니다.
추가 설명
이 문장은 DispatcherServlet이 요청에 매핑된 핸들러를 호출할 때, 핸들러를 호출하는 구체적인 방식(예를 들어, 애너테이션 해석 등)과는 무관하게 호출할 수 있도록 HandlerAdapter가 도와준다는 의미입니다.
HandlerExceptionResolver
예외를 해결하기 위한 전략으로, 예외를 핸들러, HTML 에러 뷰 또는 다른 대상으로 매핑할 수 있습니다. Exceptions를 참조하세요.
ViewResolver
핸들러가 반환한 논리적 문자열 기반의 뷰 이름을 응답을 렌더링할 실제 View로 변환합니다. View Resolution과 View Technologies를 참조하세요.
LocaleResolver, LocaleContextResolver
클라이언트가 사용 중인 Locale(지역 설정)과 필요하다면 시간대를 확인하여, 국제화된 뷰를 제공할 수 있도록 합니다. Locale을 참조하세요.
ThemeResolver
웹 애플리케이션에서 사용할 수 있는 테마를 해석합니다. 예를 들어, 개인화된 레이아웃을 제공하기 위해서입니다. Themes를 참조하세요.
MultipartResolver
일부 멀티파트 파싱 라이브러리의 도움을 받아 멀티파트 요청(예: 브라우저 폼 파일 업로드)을 파싱하기 위한 추상화입니다. Multipart Resolver를 참조하세요.
FlashMapManager
하나의 요청에서 다른 요청으로(보통 리다이렉트 간에) 속성을 전달하는 데 사용할 수 있는 “input” 및 “output” FlashMap을 저장하고 검색합니다. Flash Attributes를 참조하세요.
Web MVC Config
The DispatcherServlet checks the WebApplicationContext for each special bean. If there are no matching bean types, it falls back on the default types listed in DispatcherServlet.properties.
애플리케이션은 요청을 처리하는 데 필요한 Special Bean Types에 나열된 인프라 빈들을 선언할 수 있습니다.
DispatcherServlet은 각 특수 빈에 대해 WebApplicationContext를 확인합니다. 일치하는 빈 타입이 없으면, DispatcherServlet.properties에 나열된 기본 타입으로 대체됩니다.
In most cases, the MVC Config is the best starting point. It declares the required beans in either Java or XML and provides a higher-level configuration callback API to customize it.
대부분의 경우, MVC Config가 최상의 시작점입니다. 이는 필요한 빈을 Java 또는 XML로 선언하며, 이를 사용자 정의하기 위한 상위 수준의 구성 콜백 API를 제공합니다.
Servlet Config
In a Servlet environment, you have the option of configuring the Servlet container programmatically as an alternative or in combination with a web.xml file. The following example registers a DispatcherServlet:
서블릿 환경에서는 web.xml 파일과 함께 또는 대안으로 서블릿 컨테이너를 프로그래밍 방식으로 구성할 옵션이 있습니다. 다음 예제는 DispatcherServlet을 등록합니다:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container. An abstract base class implementation of WebApplicationInitializer named AbstractDispatcherServletInitializer makes it even easier to register the DispatcherServlet by overriding methods to specify the servlet mapping and the location of the DispatcherServlet configuration.
WebApplicationInitializer는 Spring MVC에서 제공하는 인터페이스로, 구현체가 감지되어 자동으로 모든 Servlet 3 컨테이너를 초기화하는 데 사용되도록 보장합니다. AbstractDispatcherServletInitializer라는 이름의 WebApplicationInitializer의 추상 기본 클래스 구현체는, 서블릿 매핑과 DispatcherServlet 구성 위치를 지정하기 위해 메서드를 오버라이드함으로써 DispatcherServlet 등록을 더욱 쉽게 만듭니다.
WebApplicationInitializer 인터페이스: 이 인터페이스를 구현하면, 별도의 web.xml 파일 없이도 Servlet 3 컨테이너에서 애플리케이션을 자동으로 초기화할 수 있습니다. 즉, 개발자가 구현한 초기화 클래스가 자동으로 감지되어 스프링 MVC 관련 설정을 적용하게 됩니다.
AbstractDispatcherServletInitializer 추상 클래스: 이 클래스는 WebApplicationInitializer를 구현한 기본 클래스입니다. 이를 상속받아 필요한 메서드(예: 서블릿 매핑, DispatcherServlet의 설정 위치)를 오버라이드하면, DispatcherServlet의 등록 과정을 더욱 쉽게 처리할 수 있습니다.
즉, 이 구조를 사용하면 개발자가 복잡한 초기화 과정을 직접 구현하지 않아도, 스프링이 제공하는 기본 로직을 활용하여 자동으로 서블릿 컨테이너를 설정하고 DispatcherServlet을 등록할 수 있게 됩니다.
This is recommended for applications that use Java-based Spring configuration, as the following example shows:
다음 예제가 보여주듯이, Java 기반 Spring 구성을 사용하는 애플리케이션에 권장됩니다:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { MyWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
If you use XML-based Spring configuration, you should extend directly from AbstractDispatcherServletInitializer, as the following example shows:
다음 예제가 보여주듯이, XML 기반 Spring 구성을 사용하는 경우 AbstractDispatcherServletInitializer를 직접 확장해야 합니다.
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
@Override
protected WebApplicationContext createServletApplicationContext() {
XmlWebApplicationContext cxt = new XmlWebApplicationContext();
cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
return cxt;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
AbstractDispatcherServletInitializer also provides a convenient way to add Filter instances and have them be automatically mapped to the DispatcherServlet, as the following example shows:
AbstractDispatcherServletInitializer 또한 Filter 인스턴스를 추가하고 이들이 자동으로 DispatcherServlet에 매핑되도록 하는 편리한 방법을 제공합니다.
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
// ...
@Override
protected Filter[] getServletFilters() {
return new Filter[] {
new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
}
}
각 필터는 해당 구체적인 타입에 기반하여 기본 이름으로 추가되며, 자동으로 DispatcherServlet에 매핑됩니다.
AbstractDispatcherServletInitializer의 isAsyncSupported protected 메서드는 DispatcherServlet과 그에 매핑된 모든 필터에 대해 비동기 지원을 활성화할 수 있는 단일 위치를 제공합니다. 기본적으로, 이 플래그는 true로 설정되어 있습니다.
마지막으로, DispatcherServlet 자체를 추가로 사용자 정의할 필요가 있는 경우, createDispatcherServlet 메서드를 오버라이드할 수 있습니다.
추가 설명
즉, 스프링의 초기화 클래스가 필터 관리, 비동기 지원 설정, 그리고 DispatcherServlet의 커스터마이징을 얼마나 편리하게 만들어 주는지에 대한 의미를 담고 있습니다.
참조 링크 : https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet.html
DispatcherServlet :: Spring Framework
Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components
docs.spring.io
'공식문서' 카테고리의 다른 글
[Spring Docs] DispatcherServlet #3 (0) | 2025.03.17 |
---|---|
Garbage Collector #2 (0) | 2025.03.17 |
[Spring Docs] Transaction Propagation (0) | 2025.03.14 |
Garbage Collector #1 (0) | 2025.03.09 |
[Spring Docs] Transaction Management #1 (0) | 2025.03.07 |