Spring MVC 수행 흐름
1. 클라이언트로부터의 모든 ".do" 요청을 DispatcherServlet 이 받는다.
2. DispatcherServlet 은 내장된 HandlerMapping 기능을 통해 요청을 처리할 Controller 를 검색(component-scan)한다.
3. DispatcherServlet 은 검색된 Controller 를 실행하여 클라이언트의 요청을 처리 한다.
4. Controller 는 전달받은 클라이언트 데이터를 추출하고, 서비스의 메소드로 전달한 다음 비지니스 로직의 수행결과로
리턴된 정보를 Model 객체에 저장하고 Model을 보여줄 View 정보를 ModelAndView 객체에 저장 또는 View파일명을
DispatcherServlet 으로 리턴한다.
5. DispatcherServlet 은 ModelAndView 로부터 View 정보를 추출하거나 리턴된 View파일명을 내장된 ViewResolver을 이용하여 응답할 View를 지정된 View 폴더 아래에서 찾는다.
6. DispatcherServlet은 ViewResolver를 통해 찾아낸 View를 실행하여 응답을 전송한다.
7. 응답된 View 페이지는 jsp, el, jstl, ajax, javascript, html 을 이용해 브라우저에 결과를 출력한다.
DispatcherServlet 등록 및 Spring 컨테이너 구동
WEB-INF/web.xml 파일에 등록된 정보를 수정한다.
<web.xml>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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
classpath:applicationContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
어노테이션 관련 설정
DispatcherServlet에 <annotation-driven/> 등록을 확인한다.
<annotation-driven />
Controller 클래스가 검색 범위에 포함되도록 하고자 <context:component-scan> 엘리먼트의 base-package속성에
Controller 클래스들이 있는 가장 상위 패키지를 등록한다.
<context:component-scan base-package="org.kh.member" />
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<tx:annotation-driven/> <!-- 트랜잭션 -->
<task: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>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10485760"/>
</beans:bean>
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<context:component-scan base-package="org.kh.member" />
</beans:beans>
@Controller 사용하기
클래스 선언부 위에 "@Controller" 를 붙이면 된다.
@RequestMapping 사용하기
클라이언트의 "login.do" 요청에 대해 loginMethod()가 실행되도록 하려면 @RequestMapping 을 이용하여
HandlerMapping 설정을 대체한다.
HandlerMapping 은 Servlet에서의 @WebServlet("login.do") 즉, Servlet의 url-pattern 을 의미한다.
@RequestMapping 은 메소드 위에 설정한다. value 속성은 대부분 생략한다.
클라이언트 요청 처리
대부분 Controller 는 사용자의 입력 정보를 추출하여 VO(Value Object)에 저장한다.
그리고 비지니스 컴포넌트의 메소드를 호출할 때 VO 를 인자로 전달한다.
사용자 입력 정보는 HttpServletRequest의 getParameter() 메소드를 사용하여 추출한다.
그런데 사용자 입력 정보가 많을 경우와 입력 정보가 변경될 때마다 Controller 의 추출 코드가 수정되어야
할 것이다.
Command 객체를 이용하면 이런 문제를 해결할 수 있다.
Command 객체는 Controller 의 메소드 매개변수로 받은 VO 객체라고 보면 된다.
스프링 컨테이너가 해당 메소드를 실행할 때 Command 객체를 생성하고 사용자가 입력한 값들을 Command
객체에 셋팅까지 해서 넘겨준다.
즉, 사용자 입력정보 추출과 VO 객체 생성, 추출값 셋팅 모두를 스프링 컨테이너가 자동으로 처리한다는 것이다.
여기서 중요한 것은 FORM 태그 안의 INPUT 태그의 NAME 속성의 이름과 VO 객체의 필드명이 반드시 일치 해야한다.
그리고 각 필드의 Setter 메소드가 반드시 존재해야 한다.
비지니스 컴포넌트 사용
Spring IoC 에서의 비지니스 컴포넌트는 VO 클래스, DAO 클래스, Service 인터페이스, Service 구현 클래스 4개의
파일로 구성되어 있다.
그리고 Controller는 DAO 를 직접 이용해서는 안되며 반드시 비지니스 컴포넌트를 이용해야 한다.
이유는 비지니스 컴포넌트에 다형성을 적용하여 클라이언트가 인터페이스를 통해서 비지니스 컴포넌트를 이용하면 컴포넌트 구현 클래스(인터페이스 후손클래스)를 수정하거나, 다른 구현 클래스로 대체해도 이를 사용하는 클라이언트는 수정하지 않아도 되기 때문이다. 즉 비지니스 컴포넌트가 수정되더라도 이를 사용하는 Controller 는 수정하지 않아도
되게 하려는 것이다.
Service 인터페이스를 작성하고 나서, Service 인터페이스를 상속받은 Service 구현클래스 이름 위에 @Service("서비스이름") 어노테이션을 표시한다. DAO에서는 @Repository("DAO이름") 어노테이션을 표시한다.
'이공계전문기술연수 > Spring Framework' 카테고리의 다른 글
<이공계기술전문연수> Spring (Mybatis 연동) / 동적쿼리 (0) | 2019.11.27 |
---|---|
<이공계기술전문연수> Spring MVC(View 흐름) (0) | 2019.11.26 |
<이공계기술전문연수> Spring과 외부 라이브러리 연결 (0) | 2019.11.26 |
<이공계기술전문연수> Spring MVC 설정 (0) | 2019.11.26 |
<이공계기술전문연수> 1. Framework 특징 (0) | 2019.11.19 |