archive
Spring MVC 구조 본문
브라우저(클라이언트)에서 request가 들어오면, 가장 먼저 DispatcherServlet으로 전달된다.
DispatcherServlet에서는 이를 HandlerMapping에 전달한다.
HandlerMapping에서는 요청을 처리하기 위해 적합한 Controller를 선택한다. (@Controller)
HandlerAdapter에서는 해당 Controller에서 적합한 메서드를 선택한다. (@RequestMapping)
DispatcherServlet은 해당 Controller에 요청을 보낸다.
Controller의 메서드가 수행되고 난 후 model과 view(jsp)를 반환한다.
DispatcherServlet에서 ViewResolver에 전달하여, 처리결과를 출력할 view를 선택한 후,
respose를 생성하여 클라이언트에게 응답을 보낸다.
web.xml 예시
DispatcherServlet은 WEB-INF/web.xml 에서 <servlet>, <servlet-mapping> 태그를 이용하여 매핑한다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-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>
<!-- Processes application requests -->
<!-- DispatcherServlet을 서블릿으로 등록할 때 초기 파라미터로 servlet-context.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>
<!-- Servlet 매핑 경로는 루트 경로 -->
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
이 때 초기화 파라미터로 스프링 설정파일(servlet-context.xml)을 등록하여 스프링 컨테이너를 만든다.
해당 컨테이너 안에 HandlerMapping, HandlerAdapter, ViewResolver 객체가 자동으로 생성된다.
servlet-context.xml 예시
<annotation-driven / > 태그를 통해 @Controller 어노테이션 붙은 클래스들을 컨트롤러로 인식한다.
<?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 -->
<!--ViewResolver 생성 - Jsp파일 설정 -->
<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.spring.practice" />
</beans:beans>
Controller 예시
@Controller
public class HomeController
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
"/" 경로로 들어온 GET요청에 대해 home 메서드가 실행된다.
"home" 이라는 문자열을 반환하면 viewResolver에서 prefix, suffix를 붙여줘서, /WEB-INF/views/home.jsp 뷰가 전달된다.
Controller에서는 Model 객체에 값을 담아서(addAttribute) DispatcherServlet에 전달할 수 있다.
이는 View에서 가공되어 클라이언트에게 reponse를 보낸다.
View 예시 - home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<body>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
HomeController에서 Model 객체에 넣은 serverTime의 value가 화면에 나타나게 된다. (HomeController에서 formattedDate에 해당)
톰캣 서버를 이용해 위 예제를 실행한 결과는 아래와 같다.
현재 시각이 화면에 출력된다.
'STUDY > Spring' 카테고리의 다른 글
Spring DI(의존성 주입, Dependency Injection) (0) | 2021.02.25 |
---|---|
스프링 프로젝트 EC2에 배포, 포트포워딩, 도메인 적용 (0) | 2021.02.17 |
JSON 데이터 다루기 - org.json 패키지 (0) | 2021.02.15 |
네이버 쇼핑 검색 API 이용하기 (0) | 2021.02.07 |
[JPA] 특정 기간 내의 데이터만 조회하기 (0) | 2021.02.07 |