정적 컨텐츠 방식
static - hello-static.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>

 

MVC 방식
HelloController
package hello.hellospring.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(value = "name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
}

 

templates/hello-template.html 생성

 

hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

 

 

API 방식
@ResponseBody
package hello.hellospring.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;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "hello!!");
        return "hello";
    }

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

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

    @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;
        }
    }

}

 

 

@ResponseBody를 사용

- HTTP의 BODY에 문자 내용을 직접 반환

- viewResolver 대신에 HttpMessageConverter가 동작

- 기본 문자처리 : StringHttpMessageConverter

- 기본 객체처리 : MappingJackson2HttpMessageConverter

- byer 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

 

'스프링' 카테고리의 다른 글

[Spring] AOP  (0) 2021.06.02
[Spring Boot] InteliJ 5. H2 데이터베이스 설치  (0) 2021.06.01
[Spring Boot] 3. InteliJ 빌드  (0) 2021.05.20
[SPRING BOOT] 2.InteliJ Hello 찍기  (0) 2021.05.20
[SPRING BOOT] 1. InteliJ 프로젝트 생성  (0) 2021.05.19
복사했습니다!