KKG
Programming
KKG
전체 방문자
오늘
어제
  • 전체 글 보기 (84)
    • 회고 (9)
    • Bootcamp (19)
    • Error Handling (2)
    • Kotlin (1)
    • Java (19)
      • Java (14)
      • Spring (1)
      • JPA (2)
      • Link (2)
    • Python (5)
    • 알고리즘 (20)
      • 알고리즘 (4)
      • 백준 (14)
      • 프로그래머스 (1)
      • Link (1)
    • SQL (5)
      • SQL (1)
      • MySQL (4)
    • Web (2)
    • etc (1)

블로그 메뉴

  • 태그
  • 방명록
  • 깃허브

인기 글

티스토리

hELLO · Designed By 정상우.
KKG

Programming

Java/Spring

[Spring] 정적 컨텐츠, MVC와 템플릿 엔진, API

2022. 2. 2. 14:25

정적 컨텐츠

 - html 파일을 그대로 불러와 웹페이지에 표시

 

MVC와 템플릿 엔진

 - 템플릿 엔진을 모델, 뷰, 컨트롤러 방식으로 나누어 뷰를 템플릿 엔진으로 html을 렌더링해 웹페이지에 표시

// hello-spring/src/main/java/hello/hellospring/controller/HelloController.java
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-mvc") // http://localhost:8080/hello-mvc?name=spring
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
}
<!--
hello-spring/src/main/resources/templates/hello-template.html
-->
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}" >hello! empty</p>
</body>
</html>

 

API

 - @ResponseBody를 사용하면 viewResolver를 사용하지 않고 HttpMessageConverter가 동작

 - HTTP의 BODY에 String 값을 직접 반환

 - 객체를 반환하면 객체가 JSON 형식으로 변환됨

 - String: StringHttpMessageConverter 사용

 - 객체: MappingJackson2HttpMessageConverter 사용

// hello-spring/src/main/java/hello/hellospring/controller/HelloController.java
package hello.hellospring.controller;

import org.springframework.stereotype.Controller
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-string") // http://localhost:8080/hello-string?name=spring
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello " + name;
    }

    @GetMapping("hello-api") // http://localhost:8080/hello-api?name=spring
    @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;
        }
    }

}

    티스토리툴바