본문 바로가기

Spring 공부

spring 공부 - 정적 컨텐츠, MVC, API

728x90
반응형

index.html 부터 시작함

 

템플릿 엔진: Thymeleaf

 

웹어플리케이션에서 첫번째 진입점이 controller

 

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>

 

 

 


 

웹 어플리케이션에서 /Hello 라고 들어오면 이 메소드 실행

 

@Controller
public class HelloController {
  @GetMapping("hello")
  public String hello(Model model){
    model.addAttribute("data","hello!"); // model에 담음
    // 데이타를 hello 라고 넘길 꺼다
    // 키가 data 벨류는 hello
    return "hello"; // hello.html 을 찾아감
  }
}

 

templetes/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>
//컨트롤러의 value (hello) 가 data에 치환됨
</body>
</html>

 

localhost:8080/hello

 

 

컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리한다.


스프링 부트 템플릿엔진 기본 viewName 매핑


resources:templates/ +{ViewName}+ .html

 

 

빌드 후 실행하기 (윈도우)

 

콘솔로 이동 명령 프롬프트(cmd)로 이동


./gradlew gradlew.bat 를 실행하면 됩니다.


명령 프롬프트에서 gradlew.bat 를 실행하려면 gradlew 하고 엔터를 치면 됩니다.


gradlew build


폴더 목록 확인 ls dir

 

jar 파일 만들어짐

 

 

정적 컨텐츠

<!DOCTYPE HTML>
<html>
<head>
    <title>static content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>

 

컨트롤러가 없음

 

 

MVC와 탬플릿 엔진

 

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

 

requestParam -> name
name에 hello 전달

 

http://localhost:8080/hello-mvc?name=hello

 

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

 

 

 

 

 

API

 

@GetMapping("hello-string")
    @ResponseBody // http body부에 내가 직접 넣어주겠다
    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 를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음
대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님)

 

http://localhost:8080/hello-string?name=spring

 

으로 spring을 입력받는다.

 

 

json 사용함!

 

@ResponseBody 를 사용
HTTP의 BODY에 문자 내용을 직접 반환
viewResolver 대신에 HttpMessageConverter 가 동작
기본 문자처리: StringHttpMessageConverter
기본 객체처리: MappingJackson2HttpMessageConverter
byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

 

 

 

 

 

반응형