geeone 스터디 블로그

[Spring] 강의 스터디 WIL 2주차 본문

Spring

[Spring] 강의 스터디 WIL 2주차

alisongeeone 2024. 9. 27. 13:13

섹션3. 스프링 웹 개발 기초 

1. 정적 컨텐츠
2. MVC와 템플릿 엔진
3. API

 

1. 정적 컨텐츠 

- 서버에서 하는 것 없이 그대로 페이지를 웹에 내려줌.

- 스프링 부트는 정적 컨텐츠 기능을 자동으로 제공.

 

src/main/resources/static 폴더 안에 hello-static.html 파일 만들기

->  http://localhost:8080/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>

 

 

결과 화면
정적 컨텐츠 이미지

 

-> localhost:8080/hello-static.html 요청이 들어감

-> 내장 톰켓 서버가 요청과 관련된 컨트롤러가 있는지 먼저 확인해 봄. (컨트롤러우선 순위를 가짐!) 

-> hello-static 관련 컨트롤러가 없음

-> resources: static/hello-static.html 확인 -> 있네? 반환

 

 

 

 


 

2. MVC와 템플릿 엔진

- html을 서버에서 동적으로 바꿔서 내림

- MVC : Model, View, Controller -> 요즘은 이 패턴을 쪼개는 것이 기본 (역할과 책임을 나누기 위해)

 

 

Controller : business 로직, 서버 내부적인 것을 처리하는데 집중 
 @Controller
 public class HelloController { 
 @GetMapping("hello-mvc")
     public String helloMvc(@RequestParam("name") String name, Model model) {
         model.addAttribute("name", name); //parameter로 넘어온 name을 넘김
         return "hello-template";
     }
}

 

-> @RequestParam : 외부에서 parameter를 받음

 

-> return "hello-template" 이므로 src/main/resources/templates 폴더에 hello-template.html 파일을 만들기

 

 

 

View : 화면을 그리는데 집중 

 

hello-template.html

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

-> hello! empty : hello-template.html을 절대 경로 복사해서 웹에서 열어보면 파일 자체를 열어줌. (hello! empty가 뜸)

                           : 타임리프 템플릿의 장점 : html을 서버 없이 바로 열어봐도 껍데기를 볼 수 있음~

                           : 템플릿 엔진으로 동작하게 되면, hello! empty가 'hello'+${name}으로 치환됨

 

 

 

localhost:8080/hello-mvc : 에러가 남

 

 

 

 

에러 이유 : param이 비어있음 -> localhost:8080/hello-mvc?name=spring! 으로 바꾸기

 

 

 

Model : 화면에 필요한 것들을 담아 넘겨줌

 

결과 화면

 

 

MVC, 템플릿 엔진 이미지

 

-> 웹 브라우저에서 localhost: 8080/hello-mvc 넘김

-> 내장 톰캣 서버가 스프링한테 전달

-> helloController의 hello-mvc가 매핑되어 있으므로 그 메서드를 호출

-> return을 hello-template 으로 하므로 스프링이 viewResolver가 templates/hello-template.html을 찾아서 타임리프 템플릿 엔진에 넘김

-> 타임리프 템플릿 엔진이 랜더링, 변환해서 웹 브라우저에 반환

 

 

 

 


3. API

 

: 템플릿 없이 그대로 데이터를 내려줌.

: 서버끼리 통신할 때 많이 사용

 

src/main/java/hello.hellospring/controller/HelloController에 추가

@GetMapping("hello-string")
     @ResponseBody //적어줘야 함. http의 body 부에 직접 이 내용을 넣겠다. 
     public String helloString(@RequestParam("name") String name) {
         return "hello " + name; 
         }

 

@ResponseBody : http(html 아님)의 body 부에 "hello"+name 이라는 데이터를 직접 넣겠다.

결과화면 :   http://localhost:8080/hello-string?name=spring

-> MVC&템플릿 엔진과의 차이점 : view 와 상관없이 요청한 클라이언트에게 데이터가 그대로 넘어감. 

 

'MVC' 에서 페이지 소스 보기

 

 

'템플릿 엔진'에서 페이지 소스 보기

 

 

 

src/main/java/hello.hellospring/controller/HelloController에 추가

<json 방식> : key-value로 이루어진 구조

	@GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name){
        Hello hello=new Hello();
        hello.setName(name); //파라미터로 넘어온 name 넣기
        return hello; //객체 반환

    }

    static class Hello{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

 

- command+N : Getter, setter 만들 수 있음. // 자바 빈 표준 방식

- command+shift+enter : intelliJ에서 코드 줄을 완성 해줌.

 

결과화면 : http://localhost:8080/hello-api?name=spring

 

ResponseBody 사용 방식

 

-> 웹 브라우저에서 localhost: 8080/hello-api를 침

-> 내장 톰캣 서버가 스프링에 던짐

-> hello-api에 매칭

-> @ResponseBody 가 붙어 있으므로 viewResolver를 사용하지 않음.

-> 객체를 반환하는 코드일 때는, default로 json 방식으로 데이터를 만들어서 http 응답에 반환하겠다는 것이 기본 정책.

-> viewResolver 대신에 HttpMessageConverter 가 동작 (단순 문자면 StringConverter가 동작, 객체면 JsonConverter가 기본으로 동작)

-> Json으로 바꾼 것을 웹 브라우저에게 보냄

 

 

@ResponseBody 를 사용

  • HTTP의 BODY에 문자 내용을 직접 반환
  • 기본 문자처리: StringHttpMessageConverter
  • 기본 객체처리: MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음
  • @ResponseBody 를 사용하면 뷰 리졸버( viewResolver )를 사용하지 않음
  • 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님)
  • 즉, @ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환됨