Ch 03. 스프링 MVC 분석
3.1 스프링 MVC의 프로젝트 구조
3.2 웹 프로젝트 환경 설정 파일: web.xml
3.3 스프링 MVC 환경 설정 파일
3.4 컨트롤러: HomeController.java
3.5 뷰: hello.jsp
3.1 스프링 MVC의 프로젝트 구조

1. web.xml 파일에 웹 브라우저(클라이언트)의 웹 요청 URL 전달
web.xml 파일에 설정된 디스패처 서블릿이 클라이언트의 웹 요청 URL 제어
2. servlet-context.xml 파일에서 웹 요청 URL을 처리하는 컨트롤러에 해당하는 클래스 검색
3. HomeController 컨트롤러가 클라이언트의 웹 요청 URL을 처리하고 결과를 출력할 뷰 이름을 디스패처 서블릿에 반환
4. 컨트롤러에서 보내온 뷰 이름을 토대로 처리할 뷰 검색
5. 처리 결과가 포함된 뷰를 디스패처 서블릿에 반환하고 최종 결과 출력
3.2 웹 프로젝트 환경 설정 파일: web.xml
3.2.1 네임 스페이스와 스키마 선언
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
<!-- 기본 네임 스페이스 선언 -->
xmlns="http://java.sun.com/xml/ns/javaee"
<!-- 인스턴스 네임 스페이스 URI 선언 -->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- 참조하는 인스턴스 문서의 URI 선언 --> <!-- 스키마 파일 이름 -->
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
3.2.2 루트 컨텍스트 설정
루트 컨텍스트: 모든 서블릿과 필터가 공유할 수 있는 루트 스프링 컨테이너 설정. 공통 빈(Service, Repository(DAO), DB, Log, Security 등) 설정
<context-param>: 기본 설정 외에 사용자가 직접 제어하는 XML 파일 지정
<!-- 공용 객체를 담을 컨테이너 설정 파일 지정 -->
<!-- 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>
3.2.3. 서블릿 컨텍스트 설정
서블릿 컨텍스트: 서블릿 하나가 서블릿 컨테이너와 통신할 때 사용하는 메서드들을 가지고 있는 클래스. 웹 애플리케이션 안에 있는 모든 서블릿을 관리(서블릿 생명 주기 관리)하고 정보를 공유할 수 있게 도움
<!-- 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>
3.3 스프링 MVC 환경 설정 파일
3.1.1 root-context.xml
root-context.xml에 등록된 빈들은 모든 컨텍스트에서 공유
뷰(JSP 웹페이지)와 관련 없는 빈 객체(서비스, 저장소, 데이터베이스, 로그 등) 비즈니스 로직을 위한 컨텍스트 설정
다른 웹 컴포넌트들과 공유하는 자원들을 선언
<?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>
3.1.2 servlet-context.xml
서블릿 컨텍스트에서만 사용
뷰(JSP 웹페이지)와 관련 있는 빈 객체(컨트롤러, MultipartResolver, Interceptor, URI)와 관련 설정을 담는 클래스 설정
(1) 웹 요청을 직접 처리할 컨트롤러 지정
(2) 핸들러 매핑 설정
(3) 뷰 처리 설정(ViewResolver)
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<annotation-driven>: @Controller, @RequestMapping 같은 애너테이션을 사용할 때 필요한 빈 객체들을 자동으로 등록
context:component-scan 요소가 자동으로 인식하는 애너테이션
@Component: 컴포넌트임을 알려줌
@Repository, @Service, @Controller: DB 작업 관련/서비스 관련/MVC 컨트롤러 컴포넌트임을 의미
정적 리소스 설정
HTML, CSS img, JS 등 리소스 파일을 디스패처 서블릿의 매핑에서 제외한다.(주소창에서 경로를 입력해서 직접 접속 가능)
<!-- 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.springmvc.controller" />
component-scan 미사용시 수동 등록
<beans:bean class="com.springmvc.controller.HomeController"/>
3.4 컨트롤러: HomeController.java
컨트롤러: 클라이언트 요청을 처리할 자바 클래스
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//컨트롤러임을 명시
@Controller
public class welcomecontroller {
//URL 패턴 함수에 매핑
@RequestMapping(value ="/home", method = RequestMethod.GET)
//뷰 이름 String으로 리턴
public String welcome(Model model) {
//뷰로 값 전달
model.addAttribute("greeting", "Welcome to BookMarket");
model.addAttribute("strapline", "Welcome to Web Shopping Mall!");
//뷰 이름. String으로 리턴
return "welcome";
}
}
3.5 뷰: hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 내장 객체에 있는 요소 바로 사용 -->
${greeting}
${strapline}
</body>
</html>
3.6 메이븐 환경 설정 파일: pom.xml
3.6.1 프로젝트 정보: <project>
<!-- 모델 버전: POM 모델 버전 -->
<modelVersion>4.0.0</modelVersion>
<!-- 그룹 ID: 스프링 MVC 프로젝트 생성시 입력한 그룹의 도메인 이름 -->
<groupId>com.springmvc</groupId>
<!-- 아티팩트 ID: 프로젝트에 할당한 고유 ID -->
<artifactId>bookmarket</artifactId>
<!-- 패키지 유형 -->
<packaging>war</packaging>
<!-- 프로그램 버전 -->
<version>0.0.1-SNAPSHOT</version>
<!-- 프로젝트 이름 -->
<name>bookmarket Maven Webapp</name>
3.6.2 속성 정보: <properties>
<properties>
<java-version>17</java-version>
<org.springframework-version>4.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
변수로 사용시 ${org.springframework-version}과 같이 사용
3.6.3 의존성 라이브러리 정보: <dependencies>
각각의 의존성 라이브러리 정보는 <dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
3.6.4. 빌드 정보: <build>
프로젝트를 빌드할 때 필요한 요소
이클립스 프로젝트 생성 플러그인 설정, 소스 코드 컴파일 플러그인 설정, 자바 프로그램 실행 자바 플러그인 설정
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>17</source>
<target>17</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
'정리노트' 카테고리의 다른 글
[스프링]MVC (0) | 2024.01.18 |
---|---|
[Spring] MVC 실습① (0) | 2024.01.17 |
[스프링] 스프링 MVC (0) | 2024.01.15 |
[스프링] Spring 설치 및 Maven Project 생성 (0) | 2024.01.12 |
[깃허브] (0) | 2024.01.11 |