Spring MVC Model 동작원리
ㅇㄹ
1. DispatcherServlet 가 Client의 요청을 받고, web.xml에 등록된 DispatcherServlet <url-pattern>에 등록된 내용만 가로챈다.
2. DispatcherServlet이 가로챈 요청을 HandlerMapping에게 보내서 해당 요cjd을 처리할 수 있는 알맞은 Controller를 찾는다.
4. 컨트롤러에 의해서 실행될 로직이 처리가 된다.
( controller -> service -> dao -> db -> dao -> service -> controller )
5. 로직 처리 후 Controller는 요청받을 View의 이름을 리턴하고, ViewReciver가 보여줄 View(JSP파일)을 찾음
6. View화면을 최종 클라이언트에게 전송
hoem.jsp 동작원리
실제 프로젝트에 있는 home.jsp를 직접 실행시키면(http://localhost:8080/views/home.jsp) 404 에러가 발생한다.
-> WEB-INF 폴더에는 중요한 설정 파일이 들어있고 외부에서 직접 접근이 불가능 하게 되어있다.
1. web.xml ( DispatcherServlet )
2. servlet-context.xml ( Handler Mapping )
3. HomeControlelr ( Controller )
4. Servlet-context.xml
5. web.xml
뷰 이름이 최종적으로 DispatcherServlet으로 넘어가고, 브라우저로 전달되어 home.jsp를 볼수 있음
Code
web.xml
<?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 -->
<servlet>
<!--
< DispatcherServlet >
- Controller로 요청이 넘어가기 전 DispatcherServlet에서 요청을 가로채고, 요청이 servlet-context.xml로 전달됨
-->
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- DispatcherServlet에서 사용할 자원 설정 -->
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> <!-- Servlet-context.xml -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 요청 URL 패턴을 지정하는 부분. 만약 xxxx.do이렇게 요청하도록 지정하고 싶으면 url-pattern에 *.do 로 지정하면 된다.-->
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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-dirven>
- URL 매핑이 일어남
- annotation-diven에 의해 @RequestMapping을 사용할 수 있게 된다.
- @RequestMapping에 지정된 URL로 브라우저의 요청 URL이 매핑되게 된다.
- 아래 부분을 지우면 URL을 찾을수 없다는 오류가 발생함
-->
<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 -->
<!--
- HomeController에서 넘겨진 home은 servlet-context로 전달된다.
- InternalResourceViewResolver 를 통해서 뷰를 찾게 된다.
- 전달받은 home : /WEB-INF/views/home.jsp, WEB_INF 아래에 views 폴더에 있는 home.jsp파일의 경로를 뷰이름으로 만들게 된다.
- 새롭게 만들어진 뷰 이름은 DispatcherServlet으로 전달된다.
-->
<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>
<!--
< components-scan >
- @Controller, @Repository, @Service, @Component 어노테이션이 사용된 클래스를 자동으로 스캔하여 빈으로 등록한다.
- com.spring.example로 지정 : 해당 패키지 아래에서 어노테이션이 사용된 클래슬르 찾아서 빈으로 등록하겠다.
-->
<context:component-scan base-package="com.spring.zero" />
</beans:beans>
HomeController.java
package com.spring.zero;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
* 응용 프로그램 홈 페이지에 대해 요청을 처리합니다
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
* 뭐라카노
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
// 현재 날짜와 시간을 가져와 문자열을 만든뒤 작업의 결과를 model에 담고 home이라는 뷰이름을 반환한다.
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
// 모델객체에 특정이름을 지정하여 뷰에서 이름을 이용해 객체를 처리할 수 있게 한다
// model.addAttribute(객체)로도 사용가능한데, 이럴경우 객체명의 맨 앞 글자를 소문자로 처리한것을 이름으로 해서 사용가능한다.
return "home"; // home 반환
}
}
https://intro0517.tistory.com/151
Spring Framework (스프링프레임워크) 기본 동작 순서 및 구조
Spring Framework (스프링프레임워크) 기본적인 동작 순서 및 구조에 대해서 정리해봤습니다. 전체적인 구조가 잘 정리되어있는 블로그가 있어서 이미지와 PDF 파일을 참고했습니다. ( 이미지 및 파일 출처 : http..
intro0517.tistory.com
http://egloos.zum.com/springmvc/v/504151
@MVC와 DispatcherServlet에 대해서
이전 장까지 MyBatis와 커넥션풀의 활용, 그리고 트랜잭션에 대해 상세히 알아보았습니다. 개인적으로 이 정도의 환경이라면 소, 중형 서비스 구축에는 문제없을 정도로 환상적인 제작환경이 구축됬다고 할 수 있겠네요. 또 실제로 많은 웹개발자들이 이런 포맷을 사용하고 있구요. 이제 우리가 해야 할 것은 누구나 탐낼만한 좋은 개발환경을 구축했으니 드문드문
egloos.zum.com
'웹' 카테고리의 다른 글
echart (0) | 2021.09.12 |
---|---|
웹 개발 프레임워크 조사 React / Angular / Vue (0) | 2019.09.26 |
POST GET 한글 처리 (0) | 2019.06.20 |
어노테이션 (0) | 2019.06.20 |
GET 과 POST의 차이 (0) | 2019.06.19 |