Web on Servlet Stack
Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonl
docs.spring.io
틀린 해석이 있다면 알려주세요. 감사합니다 😚
순서가 좀 이상하지만 스프링 웹 mvc 의 Dispatcher servlet 중에서도
컨텍스트 계층, bean type, MVC config, Servlet Config 그리고 마지막 Processing 까지 기본적인 web mvc에 대한 내용을 살펴보려고 한다
뒤에 더 읽어봐야할게 많다(^^)
기본적으로 Dispatcher Servlet 은
다른 웹 프레임 설계와 같이 front controller pattern where a central 중앙, 요청 처리를 위한 공유 알고리즘을 제공하고
이 서블릿 작업은 구성 간으한 위임 구성 요소로 수행한다
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/*");
}
}
1.1.1. Context Hierarchy
DispatcherServlet 자체 구성을 위해 WebApplicationContext 를 사용하며
이 WebApplicationContext 안에는 ServletContext 및 연관 Context링크가 있다
이 WebApplicationContext 에 액세스 해야하는 경우 RequestContextUtils static method 를 사용하여 바인딩할 수 있다
근데 보통은 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/*" };
}
}
1.1.2. Special Bean Types
특별한 콩 타입ㅎ_ㅎ
DispatcherServlet 요청을 처리하고 응답하여 렌더링 하기 위해 사용하는 특수 Bean 이 있다
HandlerMapping | Map a request to a handler along with a list of interceptors for pre- and post-processing. The mapping is based on some criteria, the details of which vary by HandlerMapping implementation. The two main HandlerMapping implementations are RequestMappingHandlerMapping (which supports @RequestMapping annotated methods) and SimpleUrlHandlerMapping (which maintains explicit registrations of URI path patterns to handlers). |
HandlerAdapter | Help the DispatcherServlet to invoke a handler mapped to a request, regardless of how the handler is actually invoked. For example, invoking an annotated controller requires resolving annotations. The main purpose of a HandlerAdapter is to shield the DispatcherServlet from such details. |
HandlerExceptionResolver | Strategy to resolve exceptions, possibly mapping them to handlers, to HTML error views, or other targets. See Exceptions. |
ViewResolver | Resolve logical String-based view names returned from a handler to an actual View with which to render to the response. See View Resolution and View Technologies. |
LocaleResolver, LocaleContextResolver | Resolve the Locale a client is using and possibly their time zone, in order to be able to offer internationalized views. See Locale. |
ThemeResolver | Resolve themes your web application can use — for example, to offer personalized layouts. See Themes. |
MultipartResolver | Abstraction for parsing a multi-part request (for example, browser form file upload) with the help of some multipart parsing library. See Multipart Resolver. |
FlashMapManager | Store and retrieve the “input” and the “output” FlashMap that can be used to pass attributes from one request to another, usually across a redirect. See Flash Attributes. |
1.1.3. Web MVC Config
DispatcherServlet 은 위의 각 특수 빈에 대한 WebApplicationContext 을 확인한다
일치하는 유형이 없으면 알아서 DispatcherServlet.properties 의 기본 유형으로 들어간다
완전 기본 구성
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// Implement configuration methods...
}
1.1.4. Servlet Config
Servlet 환경에서 DispatcherServlet 을 등록하는 코드이다
import org.springframework.web.WebApplicationInitializer;
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 구현이 감지 되면
모든 Servlet 3 컨테이너를 초기화한다
AbstractAnnotationConfigDispatcherServletInitializer 메서드를 재정의 하면 등록하기가 더 쉽다고 한다.
1. JAVA 기반
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[] { "/" };
}
}
2. xml 기반
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[] { "/" };
}
}
세가지의 컨테이너를 초기화시켜줌
Filter 인스턴트를 추가하여 자동 매핑 방법을 제공한다고 한ㄷ
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
// ...
@Override
protected Filter[] getServletFilters() {
return new Filter[] {
new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
}
}
The isAsyncSupported protected method of AbstractDispatcherServletInitializer provides a single place to enable async support on the DispatcherServlet and all filters mapped to it. By default, this flag is set to true.
Finally, if you need to further customize the DispatcherServlet itself, you can override the createDispatcherServlet method.
1.1.5. Processing
DispatcherServlet 에 대한 요청 처리 내용이다
- The WebApplicationContext is searched for and bound in the request as an attribute that the controller and other elements in the process can use. It is bound by default under the DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE key.
- The locale resolver is bound to the request to let elements in the process resolve the locale to use when processing the request (rendering the view, preparing data, and so on). If you do not need locale resolving, you do not need the locale resolver.
- The theme resolver is bound to the request to let elements such as views determine which theme to use. If you do not use themes, you can ignore it.
- If you specify a multipart file resolver, the request is inspected for multiparts. If multiparts are found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process. See Multipart Resolver for further information about multipart handling.
- An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is run to prepare a model for rendering. Alternatively, for annotated controllers, the response can be rendered (within the HandlerAdapter) instead of returning a view.
- If a model is returned, the view is rendered. If no model is returned (maybe due to a preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is rendered, because the request could already have been fulfilled.
1. controller, process 의 webApplicationContext 가 요청되어 바인딩
/ 디폴트 : DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE key 에 바인딩 됨
2. Locale 해석하기 위해 locale resolver가 바이인딩 (렌더링, 데이터 가져오기)
/해석이 필요하지않으면 안함
3. Theme Resolver
/ 사용하지않으면 무시
4. Multipart Resolver 요청에 대한 멀티파트 검사
/ MultipartHttpServletRequest 프로세스 요서에 의한 추가 처리로 래핑
5. HandlerAdapter 적절한 핸들러 검색
6. 모델이 반환되면 뷰 렌더링 , 모델 반환이 없으면 이미 이행되어있을 수 있어 렌더링되지않음
+ 예외처리 HandlerExceptionResolver+ HTTP 캐싱 지원 WebRequest 의 checkNotModified method
+ web.xml 파일 DispatcherServlet instances by adding Servlet initialization parameters
개별 DispathcerServlet instance 를 사용자 정의
DispatcherServlet initialization parametersParameterExplanationcontextClass | Class that implements ConfigurableWebApplicationContext, to be instantiated and locally configured by this Servlet. By default, XmlWebApplicationContext is used. |
contextConfigLocation | String that is passed to the context instance (specified by contextClass) to indicate where contexts can be found. The string consists potentially of multiple strings (using a comma as a delimiter) to support multiple contexts. In the case of multiple context locations with beans that are defined twice, the latest location takes precedence. |
namespace | Namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet. |
throwExceptionIfNoHandlerFound | Whether to throw a NoHandlerFoundException when no handler was found for a request. The exception can then be caught with a HandlerExceptionResolver (for example, by using an @ExceptionHandler controller method) and handled as any others. By default, this is set to false, in which case the DispatcherServlet sets the response status to 404 (NOT_FOUND) without raising an exception. Note that, if default servlet handling is also configured, unresolved requests are always forwarded to the default servlet and a 404 is never raised. |
'Web > spring' 카테고리의 다른 글
[Spring framework testing] 5. Spring TestContext Framework (1) (0) | 2023.02.09 |
---|---|
[Spring security] Architecture (0) | 2023.02.08 |
[Spring framework Web MVC docs] 1.1.8. Exceptions (0) | 2023.02.06 |
[Spring framework Testing] 2. Unit Testing (0) | 2023.02.04 |
[Spring framework Web MVC docs] 1.8. Error Responses (0) | 2023.02.04 |