[Spring] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 02 스프링 웹 개발 기초

최효정·2023년 5월 21일
0

02-1 정적 컨텐츠

웹 개발 방법 3가지
정적 컨텐츠
: 서버에 특별하게 시키는 거 없이 파일을 웹브라우저에 그대로 전달
MVC와 템플릿 엔진
: 가장 많이 하는 방식
: 서버에서 html을 조금 변형해서 웹브라우저에 전달
API
: json이라는 데이터구조 포맷으로 클라이언트에게 데이터 전달
: View, JS, React 사용 시에 API만 내려주면 화면은 client가 알아서 그림
: 서버끼리 통신할 때(html이 필요 없기 때문)

스프링 부트 정적 컨텐츠 기능

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>

정적 컨텐츠 이미지

02-2 MVC와 템플릿 엔진

MVC: Model, View, Controller

HelloController.java

@Controller
public class HelloController {

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

resources/templates/hello-template.html 생성

<html xmlns:th="http://www.thymeleaf.org">
<body>
<!--Model의 key값이 name인 것에서 값을 꺼내 치환-->
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

thymeleaf의 장점
파일의 경로를 복사해 브라우저에서 파일 자체를 바로 열 수 있다.

WARN 5240 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]

아래에서 잘못된 점을.... 찾아보세요........

파일명 바꾸고 해결..

http://localhost:8080/hello-mvc?name=spring
name=spring 이런 방식으로 파라미터를 넘겨줄 수 있다.

Controller에서 name이 spring으로 바뀌고 model에 담긴다.

02-3 API

@ResponseBody 문자 반환

HelloController.java

@Controller
public class HelloController {

    @GetMapping("hello-string")
    @ResponseBody
    // @ResponseBody 를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음
    // 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님)
    public String helloString(@RequestParam("name") String name) {
        return "hello" + name; // 이 문자가 그대로 내려감
    }
}

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


html 태그가 하나도 없음!

@ResponseBody 객체 반환

command shift enter
HelloController.java

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

@ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환됨

@ReponseBody 사용 원리

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

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

0개의 댓글