본문 바로가기
Spring Tutorial

[Spring 입문 2] 스프링 웹 개발 기초 (정적컨텐츠, MVC와 템플릿엔진, API)

by 미소5 2024. 4. 28.
  • 스프링 부트가 제공하는 Welcome Page
    • /resources/static/ 위치에 index.html 파일
    • 스프링 부트가 지원하는 정적 컨텐츠 위치에 /index.html 이 있으면 된다.

 


  • 컨트롤러에는 @Controller 어노테이션
@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "sara!!");   // model(data:sara!!)
        return "hello";     //컨트롤러에서 리턴 값으로 문자를 반환하면,
        // viewResolver가 view(templates/hello.html)을 찾아서 처리
    }
}
  • 스프링 부트 thymeleaf  viewName 매핑
    • 위치:  resources/templates/ + {ViewName} +  .html
    • return "ViewName";
      • 예시) return "hello" 이면, templates/hello.html 

 


  • 위치: resources/templates/hello.html
<!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>
  • data가 "sara!!" 로 치환된다.
    • http://localhost:8080/hello 실행 → 안녕하세요! sara!!

 

 


  • 스프링 웹 개발 세가지방식
  1. 정적컨텐츠
  2. MVC와 템플릿엔진
  3. API

 


1. 정적컨텐츠: resources/statichtml파일을 그대로 반환 (컨트롤러 없음) 

  • resources/template/ 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>

 

http://localhost:8080/hello-static.html


2. MVC와 템플릿엔진

 

  • MVC: Model, View, Controller
@Controller
public class HelloController {

	@GetMapping("hello-mvc")
	public String helloMvc(@RequestParam("name") String name, Model model) {
    	model.addAttribute("name", name);   // model(name:spring)
    	return "hello-template";
        }
}

 

  • resources/template/hello-template.html
<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

  • namespring! 으로 치환된다
  • @RequestParam 값("name") 필수!
    • http://localhost:8080/hello-mvc 실행하면 에러 
    • http://localhost:8080/hello-mvc?name=spring

 


3. API

 

  • @ResponseBody 문자 반환
    • @ResponseBody를 사용하면, HTTP의 BODY에 문자 내용("hello spring")을 직접 반환 (view 없음)
@Controller
public class HelloController {

	@GetMapping("hello-string")
	@ResponseBody   
	public String helloString(@RequestParam("name") String name) {
    		return "hello " + name; //"hello spring"
        }
}

?name=spring!!!!!!

 

  • @ResponseBody 객체 반환
    • @ResponseBody를 사용하고, 객체를 반환하면 객체가 JSON으로 변환된다. {"key" : "value"}
@GetMapping("hello-api")
@ResponseBody    //객체가 JSON으로 변환됨
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;}
}

?name=spring!!!!!!

 


  • @ResponseBody의 원리

[스프링MVC 기본 기능 10] HTTP 메시지 컨버터 (tistory.com)

 

[스프링MVC 기본 기능 10] HTTP 메시지 컨버터

뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아니라, HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다. @ResponseBody를 사용하면? HTTP

joly156.tistory.com


 

728x90
반응형