Java 11 설치 ➡️ IDE (IntelliJ 또는 Eclipse 설치)
스프링 부트 스타터 사이트 이용 ➡️ 스프링 프로젝트 생성
💻 hello-spring 실행
2023-07-12T15:52:48.700+09:00 INFO 50345 --- [ main] h.hellospring.HelloSpringApplication : Starting HelloSpringApplication using Java 17.0.7 with PID 50345 (/Users/soohykim/Desktop/Spring/hello-spring/build/classes/java/main started by soohykim in /Users/soohykim/Desktop/Spring/hello-spring)
2023-07-12T15:52:48.702+09:00 INFO 50345 --- [ main] h.hellospring.HelloSpringApplication : No active profile set, falling back to 1 default profile: "default"
2023-07-12T15:52:49.036+09:00 INFO 50345 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-07-12T15:52:49.040+09:00 INFO 50345 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-07-12T15:52:49.040+09:00 INFO 50345 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.10]
2023-07-12T15:52:49.077+09:00 INFO 50345 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-07-12T15:52:49.078+09:00 INFO 50345 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 355 ms
2023-07-12T15:52:49.204+09:00 INFO 50345 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-07-12T15:52:49.208+09:00 INFO 50345 --- [ main] h.hellospring.HelloSpringApplication : Started HelloSpringApplication in 0.647 seconds (process running for 0.791)
(1) Welcome Page 만들기
index.html
생성 (경로 : resources/static/index.html)📁 index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>
controller
패키지 생성 (경로 : hello.hellospring.controller)HelloController
클래스 생성 @Controller
선언 필요
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
📌 스프링 부트 동작 환경
- (1) 웹브라우저 : localhost:8080 입력
- (2) 스프링부트에 내장된 톰캣 서버에서 받아
/hello
확인- (3) hello Controller의
GetMapping
을 통해 url 매칭 후 메소드 실행- (4) model의
data = hello!!
return값hello
➡️ resources/templates에서hello.html
찾아 렌더링
- Thymeleaf템플릿 엔진 처리
- (5) 컨트롤러에서 return값으로 문자 반환시 viewResolver가 화면을 찾아 처리함
- 스프링 부트 템플릿엔진 기본 viewName 매핑
resources:templates/
+ {ViewName} +.html
- (참고)
spring-boot-devtool
라이브러리 추가하면,html
파일만 컴파일해줘도 서버 재시작 없이 View 파일 변경 가능
- 인텔리J 컴파일 방법 : 메뉴build ➡️ Recompile
📖 참고 📖 스프링 부트 기능 찾기
- 기능 검색 : spring.io ➡️ spring-boot ➡️ 해당 버전 ➡️ reference
- 스프링 튜토리얼
- [스프링부트 매뉴얼](https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/ html/spring-boot-features.html#boot-features-spring-mvc-template-engines)
💻 ./gradlew build
실행
💻 cd build/libs
💻 java -jar hello-spring-0.0.1-SNAPSHOT.jar
스프링 부트는 자동 정적 컨텐츠 기능 제공
서버에서 바로 html파일
그대로 전달 (프로그래밍 불가)
📁 hello-static.html
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
📌 정적 컨텐츠 동작 환경
- 스프링 부트에 내장된 톰캣 서버가 스프링 컨테이너에 html 전달
- 스프링에서
hello-static 컨트롤러
있는지 확인 ➡️ 없음- 그다음
hello-static.html
있는지 확인 ➡️ 있음, 스프링에서 웹 브라우저 전달
MVC : Model, View, Controller
📁 Controller
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
// parameter 넘기는 것을 선택으로 변경시
@Controller
public class HelloController {
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(value = "name", required = false) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
💻 http://localhost:8080/hello-mvc?name=[spring!!!](출력하고자 하는 파라미터) 실행📌 MVC, 템플릿 엔진 동작 과정
- 스프링 부트에 내장된 톰캣 서버가 스프링 컨테이너에 html 전달
- 스프링은
helloController
의 해당 메서드에 매핑 된 것을 확인 ➡️ 있음, 메서드 호출- return 값으로
hello-template
과 model(name의 값 : spring) viewResolver에게 전달- viewResolver가 뷰 찾아주고, 템플릿 연결 ➡️ 있음,
templates/return값.html
을 Thymeleaf 템플릿 엔진 처리를 위해 전달- 템플릿 엔진이 변환 후 렌더링하여 ➡️ HTML으로 반환 후 웹 브라우저 전달
@ResponseBody 사용 (ViewResolver 사용X)
대신 HTTP의 BODY 부에 해당 문자 내용을 직접 반환 (HTML의 Body 태그X)
📁 @ResponseBody 문자 반환
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
}
💻 http://localhost:8080/hello-string?name=[spring~~~](출력하고자 하는 파라미터) 실행
@ResponseBody
을 사용
Hello 객체 생성
객체를 반환하면 객체가 JSON으로 변환됨
📁 @ResponseBody
객체 반환
@Controller
public class HelloController {
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
💻 http://localhost:8080/hello-api?name=[spring~~~](출력하고자 하는 파라미터) 실행
📌 API 동작 과정
- 스프링 부트에 내장된 톰켓 서버가 스프링 컨테이너에 html 전달
- 스프링은
hello-api
있는지 확인@ResponseBody
사용시 HTTP BODY에 그대로 응답 넘김 (없다면viewResolver
에 전달)
환- HttpMessageConverter가 동작
- 기본 문자 처리 (return이 문자일 경우) : 그대로 넣어 HTTP 응답에 반환 ➡️ StringHttpMessageConverter 동작
- 기본 객체 처리 (return이 객체(hello)일 경우) : 기본 JSON 방식으로 데이터를 만들어서 HTTP 응답에 반환 ➡️ MappingJackson2HttpMessageConverter 동작
- byte 처리 등 기타
HttpMessageConverter
가 기본으로 등록- (참고) 클라이언트의 HTTP Accpet 헤더와 서버의 컨트롤러 반환 타입 정보를 조합해서
HttpMessageConverter
선택됨
📖 참고 📖 JSON
📖 참고 📖 MVC vs API 차이
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌
📖 참고 📖
💻📁📌