본문 바로가기
코딩일기/날씨앱 만들기 프로젝트

[Spring] Spring 설치 및 MVC 프로젝트 구조 설명 Part2

by 욱파이어니어 2021. 10. 15.
728x90
반응형

우리가 Part1에서 Spring이 뭔지 알았고 설치하여 프로젝트를 생성했으니 이제 해당 프로젝트가 어떤 방식으로

홈페이지를 만들었는지 확인해보자.

 

못보신 분들은 아래 링크를 통해서 확인하면 될것 같다.

https://wpioneer.tistory.com/218

 

[Spring] Spring 설치 및 MVC 프로젝트 구조 설명 Part1 (쉽게 설명)

일단 Spring 설치하는 방법에 대해 알려주기에 앞서 Part1에선 Spring 이 뭔지 부터 설명과 설치 방법을 알려주겠다. Spring 이란? 자바 플랫폼을 위한 오픈소스 애플리케이션 프레임워크로 간단하게

wpioneer.tistory.com

 

 

그럼 이제 MVC 프로젝트의 구조를 한번 살펴보자. 

 

위 사진의 숫자들은 프로젝트에서 먼저 수행되는 순서이다.

 

일단 첫번째인 web.xml에 대해서 알아보자.

 

 

 

 

web.xml

 

Web.xml은 웹페이지의 환경설정을 위한 파일이다.

이 파일은 WAS가 최초로 구동될 때 web.xml을 읽고 메모리에 로딩이 되며

모든 Spring 웹어플리케이션은 반드시 하나의 web.xml파일을 가져야만 한다.

이러한 web.xml 파일의 내부에는 다시 세분화된 설정 파일들(dispacherServlet.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 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 -->
	
	<!-- Spring 환경 설정 파일 로딩하는 부분 -->
	<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>
		<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-mapping> 에서 appServlet이라는 변수로 매핑을 시켜주었고

appServlet에 관한 설정은 바로 위에 보면 있다.

 

거기선 해당 서블렛을 DispatchServlet으로 설정한다고 되어 있고 appServlet에 관한 자세한 내용은 

/WEB-INF/spring/appServlet/servlet-context.xml에 있다고 되어 있다.

(DispatchServlet은 클라이언트의 요청(Request)을 전달 받고, 요청에 맞는 컨트롤러가 리턴 한 결과 값을 View에 전달하여 알맞은 응답(Response)을 생성하는 것이다.)

 

 

 

그럼 이제 /WEB-INF/spring/appServlet/servlet-context.xml 의 경로로 들어가서 한번 확인해보자.

 

 

 

servlet-context.xml

해당 부분은 Servlet의 요청 처리를 View와 연결 시키는 부분이다.

따라서 이부분은 Controller를 등록해서 해당 Controller에서 어떤걸 return 하느냐에 따라 이동하는 View의

화면이 달라진다.

 

 

아래 소스를 통해서 자세히 살펴보자.

 

<?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 -->
	<!-- Controller의 리턴값을 어디로 이동시켜줄지 결정하는 부분. -->
	<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.wook.weather" />
	
	
	
</beans:beans>

 

위 부분에서 <annotation-driven />은 @Annotation 방식으로 bean을 등록시킨다는 얘기이다.

(※여기서 bean은 이전에 Part1에서 설명한 부품과도 같은 존재이다.)

 

Annotation 방식의 bean 등록 종류로는 아래와 같은것들이 있다.

 

 

무튼 이제 위처럼 어노테이션으로 bean을 등록할수 있으니 우리가 Annotation으로 등록한 bean을 들어가보자.

 

처음 만든 프로젝트에서는 아마 HomeController.java 일것이다.

 

 

 

 

HomeController.java 

 

이부분은 Controller가 들어간 부분으로 View와 연결 시켜주는 부분이다.

 

소스를 통해서 자세히 보자.

@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"; //home을 리턴한다.
	}
	
}

위의 @Controller를 통해서 해당 Controller를 bean에 등록 시켰고

 

그리고 그 밑에는 @RequestMapping 이라는게 있는데 이거는 해당 value값으로 url 요청이 들어오면

해당 메소드에 집입하는것이다.

 

그래서 그 안의 로직을 처리하고 "home"이라는 String을 return 하게 된다.

 

그럼 이제 home은 어디로 가는걸까?

 

home은 우리가 servlet-context.xml에서 설정한 코드와 연관이 있다.

	<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>

아래 코드는 등록한 bean로부터 return 되는 값들 앞에 

"/WEB-INF/views/" 가 들어가고 그리고 뒤에는 .jsp가 붙는다는 얘기이다.

 

그럼 home을 return 하게 되면 리턴되는 값은 

/WEB-INF/views/home.jsp 가 리턴 된다.

 

 

그럼 이제 마지막으로 home.jsp 를 보자.

 

home.jsp 

 

이건 jsp 파일로써 사용자들에게 보여질 view를 맡는 부분이다.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!  
</h1>

<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

 

 

반응형