주제
스프링 mvc 프레임워크 기반 웹 프로젝트의 작동 구조에 대해 대략적으로 파악하기
mvc 디자인 패턴
스프링 mvc 프레임워크에서 mvc는 자바에 국한되지 않고 프로그래밍 전반에 사용되는 디자인 패턴 중 하나다.
이 패턴은 프로젝트를 model, view, controller 로 구분한다.
각 부분의 기능
controller
클라이언트의 요청을 가장 먼저 받아 처리한다.
요청의 경로 및 쿼리스트링에 따라 적절한 하위 컨트롤러로 요청을 넘겨주면
하위 컨트롤러는 주요 로직을 위해 서비스 객체들을 호출한다.
서비스 객체는 담당하는 트랜잭션 작업을 위해 하위 VO나 DAO 모듈을 호출한다.
model
controller의 요청에 따라 db와 연결하여 CRUD 작업을 수행하고 결과를 controller로 전달한다.
view
사용자에게 실제로 보여지는 화면 관련 로직을 담당한다.
controller가 전달한 데이터를 화면에 매핑한다.
의의
mvc 디자인 패턴은 model과 view 간의 종속성 및 상태 저장을 controller가 전담함으로써 양자가 분리될 수 있게 한다.
이를 통해, model과 view는 각자의 주요 비즈니스 로직을 재활용할 수 있고 유지보수에 용이해진다.
https://chartist1206.tistory.com/65
[프로그래밍 일반] MVC, MVP 웹 디자인 패턴에 대해
디자인 패턴이란? 디자인 패턴이란 프로그램을 개발할 때 발생할 수 있는 문제를 방지하고자 만든 규약이다. 프로젝트가 커짐에 따라 코드 간에 복잡하게 얽혀 있으면 무언가를 추가하거나 수
chartist1206.tistory.com
스프링 mvc프레임워크 구조
스프링 mvc 프레임워크가 사용자의 요청을 받아서 화면을 보여주기까지 다음 과정을 거친다.
dispatherServlet
모든 요청을 받는 서블릿으로 어떤 컨트롤러에 요청을 전달할지 결정하고 컨트롤러가 요청을 처리하면 거기에 맞는 view를 호출한다. 컨트롤러의 매핑과 view의 매핑을 총괄하는 역할.
handlerMapping
사용자 요청을 컨트롤러 내 어떤 핸들러로 연결할지 결정한다.
url경로, 쿼리스트링, 헤더, 바디값 등에 근거하여 분기 로직을 처리한다.
handlerAdapter
핸들러 함수의 호출방식 처리 (get, post, put, delete) 및 반환 값 처리를 결정하고
(핸들러에 인자 주입, 리다이렉트 처리)
controller
요청에 따라 호출되면 주요 비즈니스 로직을 처리하기 위해 서비스 객체를 호출한 후 데이터를 받아서 view를 명시하여 전달한다. 이를 위해 데이터, view의 설정은 다시 dispatherServlet로 전달된다.
viewResolver
controller에서 호출 요청한 view 파일을 찾아서 호출한다.
view
viewResolver에서 선택한 view를 토대로 디스패처 서블릿은 view를 호출하여 데이터를 전달한다.
view는 데이터를 매핑하여 화면을 구성하고 클라이언트에게 응답한다.
dispatcherServlet 설정
(1) 서블릿 파일 매핑 설정
디스패처 서블릿(이하 디스패처)은 클라이언트의 요청을 가장 먼저 받아서 컨트롤러에 매핑시켜주기 위한 서블릿이다.
따라서, 클라이언트 요청을 jsp나 servlet으로 매핑하는 web.xml 설정이 필요하다.
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 http://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>
<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>
</web-app>
코드를 살펴보면, init-param으로 스프링 컨텍스트 파일을 초기화하고 모든 url요청을 dispatcherServlet이 받는다.
handlerMapping, handlerAdapter는 스프링 프레임워크에서 스프링 컨테이너 설정 파일에 자동으로 설정한다.
(개발자가 스프링 설정 파일을 등록하지 않을 시, 스프링 프레임워크에서 자동으로 WEB-INF/appServlet-servlet.xml 라는 이름의 파일을 찾아서 스프링 컨테이너 설정파일로 등록한다.)
스프링 설정 파일
root-context.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
</beans>
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 http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://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.bs.lec14" />
</beans:beans>
controller 객체 설정
먼저 스프링 컨테이너 설정 파일에서 <annotation-driven/> 삽입한다.
이러면 MVC 구조 설정에 필수적인 빈 객체를 생성하여 각종 어노테이션을 사용할 수 있게 된다.
controller 객체로 사용할 클래스의 정의
컨트롤러로 사용할 클래스 상단에 Controller어노테이션을 선언한다.
@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);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
@RequestMapping
사용자의 요청url과 컨트롤러 혹은 컨트롤러 내 메소드를 매핑한다.
model 객체 파라미터 정의 및 사용
controller의 핸들러의 인자인 model은 view로 전달되는 데이터 역할을 한다.
모델 객체에 model.addAttribute(key, value) 로 데이터를 적재할 수 있다.
view resolver 설정
스프링 컨테이너 설정파일에서 다음같이 설정한다.
<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>
위처럼 설정할 시, controller에서 리턴하는 값과 조합하여 view 역할을 할 jsp을 찾아간다.
예컨대, 아까 home 핸들러에서 "home"을 리턴하면,
view resolver는 /WEB-INF/views/home.jsp 를 호출한다. 그리고 model 데이터를 view로 넘겨준다.
'java > spring' 카테고리의 다른 글
[spring] 쿠키, 세션, 리다이렉트, 인터셉트 (0) | 2024.06.09 |
---|---|
[spring] 스프링 mvc웹 서비스 만들기 (sts없이 수동 설정) (0) | 2024.06.09 |
[spring] 어노테이션을 이용한 스프링 설정 (0) | 2024.06.09 |
[spring] 스프링 컨테이너의 생명주기 (0) | 2024.06.05 |
[spring] 의존 객체 주입(Dependency Injection, DI) (0) | 2024.06.01 |