느린 것을 걱정하지 말고, 멈춰서는 것을 걱정하라
article thumbnail
Published 2019. 11. 25. 08:51
Spring MVC 프레임워크 IT/SpringFramework

어제 토비의스프링 vol2 3장 스프링 MVC에 대하여 공부를 하였다. 공부를 수행한 시각은 약 2뽀모도리(1시간 가량)이다. 50분가량 공부하면서 느낀점은 내가 스프링에 대해 빙산의 일각정도의 지식만 갖고 프로젝트를 임해왔었다는 것이다.

 

토비의 스프링을 보기전에 본 책은 토비의 스프링 1/6분량의 얇은 책이었는데 지금와서 생각해보면 필요한 내용은 모두 담겨있었으나 토비의 스프링처럼 통찰을 갖다주는 책이 아닌 레퍼런스의 번역서 정도로 생각할 수 있을것 같다. 

오늘 2뽀모도리동안 공부한 양에 내가 기본적으로 알고있던 내용보다 더 많은 통찰을 얻게되었고 아직 공부할 것이 많이 남아 있다는 점에서 얼마나 모르고 있었는지 반성하게 된다.

 

스프링의 MVC 패턴은 아래의 그림과 같이 동작한다.

 

스프링 웹 MVC가 수행되는 과정

  1. 외부로부터 DispatcherServlet으로 Http요청이 온다.

  2. HandlerMapping클래스가 http요청을 해석하여 요청에 따라 어떠한 Controller가 작업을 수행할 지 결정한다.

  3. Servlet과 Controller사이에 Handler Interceptor체인이 있는데 Tomcat Filter와 비슷한 역할을 하지만 Controller로 부터 반환되는 Model, View등에 추가작업을 하는등 더욱 세밀한 필터링이 가능
  4. Controller가 서비스, 데이터액세스 객체에게 작업을 위임하여 비즈니스 로직을 처리한 후 Model 과 View 정보를 반환한다.

  5. ViewResolver가 Controller로 부터 반환된 Model과 View 정보를 바탕으로 View 객체를 생성한다.

  6. 일반적으로 자바 웹 프로젝트에서 jsp를 뷰로 사용하지만 스프링에서는 JstlView객체가 jsp를 템플릿으로 하여 HTML을 생성하여 반환한다. 그렇기 때문에 모델등의 데이터가 jsp에 ${} 치환식으로 표현이 가능한 것으로 보임.

 

자, 그럼 이 스프링 웹 MVC에서 빈은 어디서 어떤 빈들을 생성되는 것일까 하는 궁금증이 생겨서 소스코드를 살펴보니까 DispatcherServlet에서 다음과 같이 servlet-context.xml 설정 파일을 참고해서 빈을 생성한다.

 

[web.xml]

````````````````` 중략 `````````````````
<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>
````````````````` 중략 `````````````````

[/WEB-INF/spring/appServlet/servlet-context.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
              http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
       <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
       
       <!-- Enables the Spring MVC @Controller programming model -->
       <annotation-driven />
       <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
       <resources mapping="/resources/**" location="/resources/" />
       <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
       <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <beans:property name="prefix" value="/WEB-INF/views/" />
              <beans:property name="suffix" value=".jsp" />
       </beans:bean>
       
       <context:component-scan base-package="com.copocalypse.www" />
                     
</beans:beans>

 

 그리고 책에서는 웹과 관련된 빈을 서비스와 관련된 빈 설정을 분리하라고 하는데 이는 listener를 이용해서 빈을 생성하고 있다.

(참고로, ContextLoaderListener는 ServletContextListner인터페이스를 상속받아서 WAS가 최초 로드 될 때 필요한 초기 작업이나 WAS가 종료될 때 특정 작업을 수행할 수 있다.)

 

[web.xml]

``````````````` 중략 ```````````````
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/*-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>
``````````````` 중략 ```````````````

 

[root.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
       
       <bean id="myBean" class="com.copocalypse.www.util.MyBean"/>
                     
</beans>

 

공부하면서 내가 가진 지식을 체계화 할 수 있었는데 지식 체계화 과정을 거치면서 새롭게 얻은 지식은 다음과 같다.

  1. HandlerMapping에서 Handler란 곧, Controller를 말함

  2. jsp파일은 뷰가아니라 JstlView의 템플릿으로 사용됨.

 

profile

느린 것을 걱정하지 말고, 멈춰서는 것을 걱정하라

@주현태

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!