Spring Framework 프로젝트 예제를 프로젝트 만들기 부터 자세하게 보여줘.
ChatGPT의 말:
좋습니다!
여기서는 Eclipse + Maven 환경에서 Spring Framework 기반의 웹 프로젝트를 만드는 전 과정을 예제 중심으로 상세하게 안내해드릴게요.
✅ 목표
- Spring Framework 기반의 웹 프로젝트를 Eclipse에서 생성
- HelloController를 만들어 웹 브라우저에 "Hello, Spring!" 출력
🛠️ 1. 개발 환경 준비
도구 | 버전 권장 |
---|---|
JDK | Java 8~17 (Spring Framework 5는 Java 8 이상 필요) |
Eclipse IDE | 최신 버전 |
Maven | Eclipse에 포함되어 있음 |
Tomcat | 설치 또는 Eclipse 내장 서버 사용 |
✅ 2. Maven 기반 Spring 프로젝트 만들기
📍 Eclipse에서 새 프로젝트 생성
- File > New > Maven Project
- Create a simple project (skip) 체크 ☑ → Next
- 다음 정보 입력:
- Group Id: com.example
- Artifact Id: spring-web-demo
- Packaging: war ← 중요!
- Finish
이로써 Maven 기반의 웹 프로젝트가 생성됩니다.
✅ 3. pom.xml 설정
pom.xml 열고 아래처럼 수정:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-web-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.30</version>
</dependency>
<!-- Servlet API (provided) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JSTL (optional) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>spring-web-demo</finalName>
</build>
</project>
✅ 4. 폴더 구조 만들기
Eclipse에서 아래 구조로 디렉터리와 파일 생성:
src/
└─ main/
├─ java/
│ └─ com/example/controller/
│ └─ HelloController.java
├─ resources/
└─ webapp/
├─ WEB-INF/
│ ├─ web.xml
│ └─ dispatcher-servlet.xml
└─ index.jsp
✅ 5. web.xml 설정 (서블릿 설정)
src/main/webapp/WEB-INF/web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
✅ 6. Spring 설정 파일 dispatcher-servlet.xml
src/main/webapp/WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Controller 검색 -->
<context:component-scan base-package="com.example.controller" />
<!-- 기본 MVC 설정 (ViewResolver 등) -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
✅ 7. Controller 클래스 만들기
HelloController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring!");
return "hello"; // → /WEB-INF/views/hello.jsp
}
}
✅ 8. JSP View 파일 생성
/WEB-INF/views/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Hello</title></head>
<body>
<h1>${message}</h1>
</body>
</html>
index.jsp는 기본 환영 페이지로 간단히 만들어 둡니다.
✅ 9. Tomcat 설정 후 실행
- Eclipse의 Servers 뷰에서 Tomcat 추가
- 프로젝트를 서버에 추가
- 실행 → 브라우저에서 http://localhost:8080/spring-web-demo/hello 접속
🎉 결과
📌 요약
단계 | 설명 |
---|---|
1 | Maven WAR 프로젝트 생성 |
2 | Spring 의존성 추가 |
3 | web.xml, Dispatcher 설정 |
4 | Controller + JSP 뷰 작성 |
5 | Tomcat 실행 후 접속 확인 |
이제 Spring Framework 프로젝트를 직접 실행해볼 수 있습니다.
위의 예제의 경우 index.jsp가 없어도 동작을 하는 이유는?
ChatGPT의 말:
아주 좋은 질문입니다!
예제에서 index.jsp가 없어도 동작하는 이유는, 기본 루트 URL /에 매핑된 컨트롤러가 없기 때문입니다. 다시 말해:
✅ 동작의 흐름 정리
당신의 컨트롤러는 다음과 같습니다:
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring!");
return "hello"; // /WEB-INF/views/hello.jsp
}
}
즉, 클라이언트가 http://localhost:8080/spring-web-demo/hello 로 요청을 보내야 정상 작동합니다.
🚫 그런데 index.jsp가 없으면 / 요청은 어떻게 될까?
- 브라우저에서 http://localhost:8080/spring-web-demo/ 로 요청을 보내면,
/ 경로를 처리할 컨트롤러가 없으므로 404 오류 또는 No mapping 경고가 뜹니다. - index.jsp는 단지 정적 환영 페이지로 사용되는 것이며,
Spring MVC에서 / 경로를 처리하도록 지정된 컨트롤러가 없으면 전혀 필요하지 않습니다.
✅ 왜 여전히 /hello는 잘 작동하는가?
- /hello 경로에 매핑된 컨트롤러가 존재하고,
- 해당 경로를 DispatcherServlet이 처리하도록 되어 있으며,
- 뷰 리졸버가 JSP를 찾아주기 때문에,
- index.jsp가 없어도 /hello 요청은 문제 없이 작동합니다.
🔍 보통 index.jsp는 언제 필요한가?
- 웹 루트 /로 접속했을 때 기본 화면을 보여주고 싶을 때
- 컨트롤러가 매핑되지 않은 정적 초기 페이지가 필요할 때
- JSP 기반의 전통적인 MVC에서 자동 로딩하려 할 때 (web.xml에서 welcome-file-list로 설정)
예시:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
하지만 Spring MVC 컨트롤러에서 /에 매핑된 메서드를 만들면 index.jsp는 필요 없습니다.
🧩 요약
상황 | 설명 |
---|---|
/hello 요청 | @GetMapping("/hello") 가 처리하므로 index.jsp 필요 없음 |
/ 요청 | 해당 경로 매핑이 없으면 404 발생 index.jsp가 있으면 대신 보여줌 |
index.jsp의 역할 | 루트 경로 요청 시 기본 페이지 역할 (컨트롤러가 없을 때 한정) |
Spring 방식 권장 | / 매핑용 컨트롤러 만들어서 초기 화면 처리 |
필요하시면 / 경로를 처리하는 기본 컨트롤러 예제도 바로 드릴 수 있어요.
'전자정부 프레임워크 공부' 카테고리의 다른 글
Spring Framework 프로젝트 예제 - Spring MVC + MyBatis + MySQL (1) | 2025.05.22 |
---|---|
Spring Framework 프로젝트 예제 - Mysql 8 연동 (0) | 2025.05.22 |
Spring이란? (1) | 2025.05.22 |
콘솔에서 Maven 사용한다는 의미는? (0) | 2025.05.22 |
eclipse에 maven을 설치하는 방법과 사용하는 방법은? (0) | 2025.05.22 |