스프링 입문 - Ch 2. 스프링 웹 개발 기초

seren-dev·2022년 3월 20일
0

스프링 입문

목록 보기
2/11

인텔리제이 윈도우 단축키

  • 정적 컨텐츠: 파일을 그대로 줌
  • MVC와 템플릿 엔진: 템플릿 엔진은 서버에서 프로그래밍해서 html을 동적으로 바꾸어서 내려주는 것
  • API: JSON 데이터 포맷으로 클라이언트에게 데이터 전달 -> 화면은 클라이언트가 알아서

정적 컨텐츠

resources/static/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

  • 정적 파일 그대로 반환
  • 프로그래밍을 할 수 없음
  • 내장 톰캣 서버가 요청을 받고 스프링에게 넘김
  • 컨트롤러에서 찾아봄 -> 없음
  • 스프링부트가 resources: static에서 찾음
  • 찾으면 반환

MVC와 템플릿 엔진

Model, View, Controller

  • view: 화면을 그림
  • controller: 비즈니스 로직, 내부적인 것들 처리
  • model: model에 화면에 필요한 것들 담아서 화면으로 넘김

Controller

@Controller
public class HelloController {

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

@RequestParam("name")

  • Parameter 속성 중 required의 default가 true이기 때문에 기본으로 값을 넘겨줘야 함
  • required = false라면 값을 넘기지 않아도 됨

View

resources/template/hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • <p th:text="'hello ' + ${name}">hello! empty</p> : th:text="'hello ' + ${name}" 안의 값으로 hello! empty가 치환됨
    hello! empty: 서버 없이 html을 만들어서 볼 때

실행: http://localhost:8080/hello-mvc?name=spring!

  • 내장 톰캣 서버를 먼저 거침
  • 톰캣 서버가 스프링에게 줌
  • 스프링은 HelloController에서 매핑을 찾아 메소드 호출
  • return 할 때 model도 같이 넘겨줌
  • viewResolver가 동작함
  • view를 찾고 템플릿 엔진에게 처리해 달라고 넘김
  • 템플릿 엔진이 렌더링하고 변환한 html을 웹 브라우저에게 넘겨줌

API

@ResponseBody 문자 반환

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

@ResponseBody

  • @ResponseBody 를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않음 == view가 없음
  • 대신에 HTTP의 BODY에 문자 내용을 직접 반환
    - http 메시지에는 header와 body가 있음
    - body에 이 데이터를 직접 넣어줌

실행 : http://localhost:8080/hello-string?name=spring!!!
결과: hello spring!!!
페이지 소스에도 hello spring!!!만 있음

@ResponseBody 객체 반환

@Controller
public class HelloController {
    

    @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;
        }
    }
}
  • 객체를 반환하면 객체가 JSON으로 변환됨

내부 클래스는 static으로 선언해야 함
참고: Java의 내부 클래스는 static으로 선언하자

실행: http://localhost:8080/hello-api?name=spring??
결과: JSON (key-value로 이루어진 데이터 포맷)
{"name":"spring!!!"}
페이지 소스도 똑같이 {"name":"spring!!!"}


@ResponseBody 사용원리

  • 톰캣 내장 서버가 hello-api가 왔어라고 스프링에게 넘겨줌
  • @ResponseBody가 있으면 HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter가 동작
  • 문자가 아니라 객체라면? -> default는 JSON 방식으로 데이터를 만들어서 HTTP 응답에 반환
  • 단순 문자: StringHttpMessageConverter
  • 객체: MappingJackson2HttpMessageConverter
    Jackson: 객체를 JSON으로 바꾸는 라이브러리
  • JSON을 웹 브라우저에 넘김

byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있다.

참고: 클라이언트의 HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서
HttpMessageConverter 가 선택된다. 더 자세한 내용은 스프링 MVC 강의에서 설명하겠다.

  • HTTP 요청을 할 때 Accept 헤더는 나는 데이터를 이런 포맷으로 받고 싶다는 내용
    ex) xml, json ...

0개의 댓글