728x90
(간략한 정의)
정적컨텐츠
- 파일을 그대로 웹 브라우저에 전달해주는 방식
- 스프링 부트에는 정적 컨텐츠 기능 내장
- 내장 톰캣 서버를 거쳐서 열린다.(관련 컨트롤러 x)

http://localhost:8080/hello-static.html
=> 이렇게 열면 사이트 열린다

MVC와 템플릿 엔진
(Model, View, Controller)
서버에서 변형을 거친 후 html을 바꿔서 내려주는 방식
// Controller
package hello.hello_spring.controller;
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 HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name",name);
return "hello-template";
}
}
// View
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>


localhost:8080/hello-mvc뒤에 ?name=spring!으로 get방식을 이용해 값을 넣어주면 내용이 바뀐다

=> name의 값이 타고타고 바뀌어 View에 있는 ${name}의 값으로 되는 원리
(${~}는 Model에서 key value를 꺼내서 치환해주는 것이다.)
API
데이터만 내려주고 변형되는 방식
// Controller
@GetMapping("hello-string")
@ResponseBody // http의 body부에 이 데이터를 직접 넣어주겠다는 뜻
public String helloString(@RequestParam("name") String name){
return "hello " + name;
}

근데 여기서 페이지 소스 보기를 하면 html 소스가 하나도 없다.

=> 그냥 return값만 받아서 그대로 출력하는 방식 (데이터를 그대로)
// Controller
@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;
}
}
}

'Coding > Spring(Boot)' 카테고리의 다른 글
| [Spring]DI(의존성 주입)와 Bean (0) | 2024.06.10 |
|---|---|
| [Spring]회원 서비스 개발(+ test case) (0) | 2024.06.10 |
| [Spring]repository test case 작성 (0) | 2024.06.09 |
| [Spring]스프링부트 build 후 실행하기 (0) | 2024.06.09 |
| [Spring]스프링부트 프로젝트 설정 (0) | 2024.06.06 |