DispatcherServlet : 서블릿 컨테이너에서 http 프로토콜을 통해 들어오는 요청들을 프리젠테이션 계층의 제일 앞에 둬서 중앙집중식으로 처리해주는 프론트 컨트롤러

 

방법은 여러 가지가 있지만 web.xml파일에 설정하는 것과 org.springframework.web.WebApplicationInitializer 인터페이스를 구현해서 사용하는 방법을 많이 사용한다.

 

1) web.xml 분석하기

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- DispatcherServlet을 클래스로하는 mvc 서블릿 -->
  <servlet>
  	<servlet-name>mvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- AnnotationConfigWebApplicationContext : bean 공장 -->
  	<init-param>
  		<param-name>contextClass</param-name>
  		<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  	</init-param>
  	<!-- 
  		contextConfigLocation은 DispatcherServlet서블릿에서만 사용할 수 있는 초기화 파라미터이다.
  		contextConfigLocation은 bean 설정 파일을 의미하고, <param-value>의 위치에 있는 설정 파일을 읽어들이겠다는 의미이다.
  		즉, DispatcherServlet의 contextConfigLocation은 WebMvcContextConfiguration 클래스이다.
  	-->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>kr.or.connect.mvcexam.config.WebMvcContextConfiguration</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- / 라는 경로로 들어오면 mvc라는 이름의 서블릿을 찾아 처리한다  -->
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

2) WebMvcContextConfiguration

package kr.or.connect.mvcexam.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"kr.or.connect.mvcexam.controller"})
public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter{
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(31556926);
		registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
		registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
		registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
	}
	
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		// /라는 이름으로 입력되면 main이 실행됨
		System.out.println("addViewControllers가 호출됩니다. ");
		registry.addViewController("/").setViewName("main");
	}
	
	/*
	 * ViewResolver 설정
	 * InternalResourceViewResolver : prefix와 suffix를 설정하여 해당 경로에 있는JSP를 뷰로 생성한다.
  	 */
	@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver() {
		// main이라는 파일을 요청하면 앞에 /WEB-INF/views, 뒤에 .jsp를 붙여서 반환해준다.
		// /WEB-INF/viewsmain.jsp 파일 반환.
		System.out.println("ViewResolver가 실행되었습니다.");
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
}

@Configuration : 해당 java파일이 설정 파일임을 알려줌

 

@EnableWebMvc : DispatcherServlet의 RequestMappingHandlerMapping, RequestMappingHandlerAdapter, ExceptionHandlerExceptionResolver, MessageConverter 등 web에 필요한 빈들을 대부분 자동으로 설정해준다.

이 외의 설정이 필요하다면 WebMvcConfigurerAdapter을 상속받는 java 설정 클래스를 만들어서 오버라이딩 후 사용하면 된다.

 

@ComponentScan : Controller, Service, Component 애노테이션이 붙은 클래스를 찾아서 스프링 컨테이너가 관리하게 해준다.

 

WebMvcConfigurerAdapter : Spring 5에서는 사용되지 않을 예정이다. 그래서 WebMvcConfigurer를 implements해서 사용해야한다.

     

addResourceHandlers : 웹 애플리케이션 루트, 클래스 경로 등의 특정 위치에서 이미지, js 및 css 파일과 같은 정적 리소스를 제공하는 핸들러를 추가한다.

 

configureDefaultServletHandling : 서블릿 컨테이너의 "기본"서블릿으로 전달하여 처리되지 않은 요청을 위임하도록 처리기를 구성한다.

 

 

 

참고 :  docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.html

 

 

 

+ Recent posts