1. 개요

오늘은 DispatcherServlet에 대해 알아보자.


2. DispatcherServlet

예전에(물론 지금도) web.xml에 servlet mapping 설정이 있었다. 떄로는 아주 많이..

하지만 스프링 시대에서는 그럴 일이 별로 없다. 어떻게 보면 web.xml의 역할이 많이 축소되었다고도 할 수 있다.

앞서 우리가 만든 프로젝트를 기준으로 보자.

2-1. WEB-INF/web.xml

servlet mapping 정보가 있다.

   <!-- 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>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

servlet mapping 정보가 1개 있다.이름은 appServlet, servlet-class는 DispatcherServlet이다. 그리고 appServlet에 맵핑되는 url-pattern은 / 이다. 즉 모든 요청을 DispatcherServlet이 받겠다는 말이다.

2-2. HandlerMapping

  • Dispatcher가 받은 요청은 HandlerMapping으로 넘어간다. 그리고 이 요청을 처리할 수 있는 Controller를 찾게 된다.
  • Controller부터는 개발된 애플리케이션 영역이다. DB 연동 등 로직 처리가 이루어지고 view로 넘어간 후에 최종적으로 DispatcherServlet를 거쳐 클라이언트에 리턴된다.

3. Resource Mapping

3-1. 이미지 추가

모든 요청을 DispatcherServlet이 받고 있다. 그런데 이미지 등의 static resource가 있다. 어떻게 해야 할까? 

일단 time.jsp에 아래 내용을 추가해보자.

<img src="/img/title-img.jpg"/>"

title-img.jpg 라는 파일을 보여주겠다는 HTML 태그이다.

그리고 우리 테스트 프로젝트 기준으로 src/main/webapp/resources 하위에 img 디렉토리를 만들고 아무 이미지나 title-img.jpg 라는 이름으로 넣어보자. 결론적으로 말하면 src/main/webapp/resources/img/title-img.jpg 라는 파일이 있어야 되는 것이다.

이제 http://localhost:8080/myfirst/time.do 를 호출한다.

결과는...

엑박이 나와야 한다.

현재 상태로는 단지 리소스 폴더 아래 어딘가에 title-img.jpg 파일을 넣어둔 것뿐, DispatcherServlet이 처리할 방법이 없다. 그럼 어떻게 해야 할까?

3-2. <resources mapping=

WEB-INF/spring/appServlet/servlet-context.xml 파일을 연다. 그러면 이런 내용이 있는데..

   <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

긴말할 것 없다. 이걸 추가한다.

   <resources mapping="/img/**" location="/resources/img/" />

그리고 다시 http://localhost:8080/myfirst/time.do 를 호춣해보자.

3-3. 정리

이런 식으로 활용 가능한 것이다.

<resources mapping="/css/**" location="/resources/css/" />
<resources mapping="/images/**" location="/resources/images/" />
<resources mapping="/js/**" location="/resources/js/" />
<resources mapping="/resources/**" location="/resources/" />