반응형
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 : http://localhost:8080/greeting
- 이 URL에 대한 응답으로 "Hello, World!"라는 인사를 HTML 페이지에 표시
- 쿼리 문자열에 'name' 파라미터를 추가하여 인사를 맞춤 설정할 수 있다.
- e.g) http://localhost:8080/greeting?name=User → "Hello, User!"라는 인사말이 표시된다.
Create a Web Controller
- Spring에서는 HTTP 요청을 컨트롤러가 처리한다.
- @Controller annotation으로 컨트롤러를 식별한다.
package com.example.servingwebcontent;
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 경로로의 GET 요청을 greeting() 메서드로 매핑
- @RequestParam : 쿼리 문자열의 'name'값을 메서드 파라미터 'name'에 바인딩
- 'name' 파라미터는 Model 객체에 추가되어 뷰 템플릿에서 접근할 수 있다.
- src/main/resources/templates/greeting.html 파일에서 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>
Add a Home Page
- 정적 리소스는 src/main/resources/static 디렉토리에 추가한다.
- index.html 파일을 생성하여 루트 URL(http://localhost:8080/)에서 제공
<!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>
반응형
'Spring' 카테고리의 다른 글
Validation in Spring Boot (0) | 2024.07.02 |
---|---|
Validating Form Input (0) | 2024.07.02 |
Mapping Requests (0) | 2024.06.26 |
REST APIs Explained - 4 Components (0) | 2024.06.26 |
Spring MVC (0) | 2024.05.20 |