본문 바로가기

Spring/Spring.io

Guide - Spring MVC를 사용하여 웹 콘텐츠 제공하기

https://spring.io/guides/gs/serving-web-content

 

Getting Started | Serving Web Content with Spring MVC

Static resources, including HTML and JavaScript and CSS, can be served from your Spring Boot application by dropping them into the right place in the source code. By default, Spring Boot serves static content from resources in the classpath at /static (or

spring.io

 

목표
URL 요청 시 HTML을 포함한 웹 페이지가 반환
  • 요청 URL : http://localhost:8080/greeting
  • 응답 : 인사말( "Hello, World!")이 포함된 웹 페이지
  • 쿼리 문자열에서 name 매개변수 이용 가능
    • 요청 URL : http://localhost:8080/greeting?name=User
    • 답 : 인사말( "Hello, User!")이 포함된 웹 페이지

 

프로젝트 초기화
  1. https://start.spring.io 접속
  2. 빌드 도구, 언어, 스프링 부트 버전 선택
  3. Dependecies 추가
  4. Generate 클릭 후 zip 파일 다운로드

- 설정 예시

 

웹 컨트롤러 생성

 

// src/main/java/com/example/servingweb/GreetingController.java

package com.example.servingweb;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

 

  • @GetMapping("/greeting")
    • HTTP GET 요청이 /greeting 경로로 들어오면 greeting() 메서드가 실행
  • @RequestParam
    • 쿼리 문자열 매개변수 name 값을 받아 greeting() 메서드의 name 파라미터에 매핑
    • required-false : 필수 입력 아님
    • defaultValue = "World" : 기본 값은 "World"
  • Model model
    • 받은 name 값을 Model 객체에 추가하여 뷰가 사용할 수 있도록 함
  • return "greeting"
    • greeting.html이라는 뷰 파일을 랜더링 하도록 지정

 

뷰 템플릿 생성

 

// src/main/resources/templates/greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="|Hello, ${name}!|" />
</body>
</html>
  • xmlns:th="http://www.thymeleaf.org"
    • HTML에서 Thymeleaf 구문을 사용하기 위한 네임스페이스를 선언
  • th:text="|Hello, ${name}!|"
    • 컨트롤러에서 전달된 name 값을 활용하여 동적 텍스트 생성
    • name 매개변수가 User라면 "Hello, User!"가 없다면 기본값 "World"가 사용된 "Hello, World!"가 출력
Spring Boot DevTools

 

웹 어플리케이션에서 가장 흔한 작업은 코드 변경, 애플리케이션 재시작, 브라우저 새로고침입니다

이 과정은 오래 걸리기에 빠르게 개선하기 위해 Spring Boot는 spring-boot-devtools를 제공합니다

 

  • 핫 스와핑 지원(코드 변경 사항을 재시작 없이 바로 적용)
  • 템플릿 엔진의 캐싱 비활성화하여 변경 사항 즉각 반영
  • LiveReload 활성화로 브라우저 자동 새로고침
  • 운영 환경 대신에 개발 환경에 적합한 기본 설정 적용
애플리케이션 실행

 

// src/main/java/com/example/servingweb/ServingWebContentApplication.java

package com.example.servingweb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServingwebApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServingwebApplication.class, args);
	}

}

 

  • @ SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
    • @Configuration : 애플리케이션 컨텍스트에서 빈을 정의하는 클래스
    • @EnableAutoConfiguration : 클래스패스 설정, 다른 Bean, 설정값 등을 기반으로 자동으로 Bean 등록
    • @ComponentScan : com.example 패키지 내에서 컴포넌트, 설정, 서비 클래스 등을 자동 검색
  • main() 메서드는 Spring Boot의 SpringApplication.run() 메서드로 애플리케이션 실행
    • XML 설정 없는 100% 자바 코드

 

실행 가능한 JAR 파일 빌드

애플리케이션은 Gradle 또는 Maven을 사용하여 실행할 수 있음

필요한 모든 종속성, 클래스, 리소스를 포함하는 실행 가능한 JAR 파일을 빌드할 수 있음

JAR 파일은 개발 생명 주기, 다양한 환경에서 전달, 버전 관리, 배포를 쉽게 만들어 줌

 

// JAR 파일 빌드 후 실행(Gradle)
./gradlew build // 1. JAR 파일 빌드
ls build/libs/ // 2. JAR 파일 이름 찾기
java -jar build/libs/servingweb-0.0.1-SNAPSHOT.jar // 3. JAR 파일 실행

 

 

애플리케이션 테스트
  • http://localhost:8080/greeting 접속 : "Hello, World!" 메시지가 표시
  • http://localhost:8080/greeting?name=User 접속 : "Hello, User!" 메시지가 표시

 

홈페이지 추가

Spring Boot는 클래스패스 내 다음 경로에서 정적 리소스(HTML, JS, CSS)를 자동 제공합니다

  • src/main/resources/static/
  • src/main/resources/public/

index.html은 웰컴 페이지 역할을 하며 http://localhost:8080/로 접속할 때 자동으로 제공

 

// src/main/resources/static/index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
</body>
</html>