본문 바로가기
기술 기록/java

Spring Boot) get - 기본 작동 원리

by Fola 2022. 3. 23.

 

 

Spring Boot 프레임 워크를 이용한 자바 웹 개발 공부를 하면서

필요할 때마다 빠르게 꺼내 볼 목적으로

3가지 방식의 get 기본 작동원리를 정리했다. 

 

IDE 내의 txt 파일로 작성한 문서를 옮겨왔고,

텍스트를 그대로 붙이기에는 가독성 문제가 있어 코드 블록으로 포장함.

 


1. 정적 페이지의 작동원리


    웹 브라우저가 get 호출 - localhost:8080/hello-static.html
        내장 톰캣 서버가 컨트롤러를 찾음
            컨트롤러가 없다면
                resources: static 아래에서 요청한 페이지 검색
                - resources: static/hello-static.html 로드





2.MVC, 템플릿 엔진 이미지


    웹 브라우저가 get 호출 - localhost:8080/hello-mvc.html
        내장 톰캣 서버가 컨트롤러를 찾음
            컨트롤러가 있다!! - @GetMapping("hello-mvc") 와 hello-mvc.html (get 주소) 이 같다!!
                return "hello-template"

                    resource: templates 아래에서 요청한 페이지 검색
                    - templates/hello-template.html 페이지 로드

                파라미터 (@RequestParam(value = "name" ...
                    8080/hello=mvc?name=fola!!!
                    fola!!! <- 이 부분
                    hello-template.html 의 ${name} 을 파라미터로 치환





3. API 방식


    1) 웹 브라우저가 get 호출 - localhost:8000/hello-string.html
        내장 톰캣 서버가 컨트롤러를 찾음
            컨트롤러가 있음 - @GetMapping("hello-string")
            그러나 @ResponseBody 어노테이션 또한 있음
            -> html 의 <body></body> 부분에 직접 넣어주겠다는 어노테이션
                return "hello " + name

                    (리턴 값의 형태가 문자열 -> StringConverter 작동)
                    html 문서 없이 그대로 출력
                        8080/hello-string?name=fola!!!!!
                        결과:

                        hello fola!!!!!

                        View page Source 로 열어봐도 위의 한 문장만 존재


            -> 이 방법은 주로 json 통신 방식에 이용됨



    2) 웹 브라우저가 get 호출 - localhost:8000/hello-api.html
        내장 톰캣 서버가 컨트롤러를 찾음
            컨트롤러가 있음 - @GetMapping("hello-api")
            그리고 @ResponseBody 어노테이션 또한 있음

                내부 코드 동작

                    return hello
                    -> return 값이 문자열이 아닌 객체
                    -> 객체의 형태를 보고 스프링이 대체로 맞춰준다.
                    -> 웬만하면 json 형태를 사용 (-> JsonConverter 작동)

                        8080/hello-api?name=fola!!!!!
                        결과

                        {"name":"fola!!!!!"}

                        역시 View page Source 열어 보아도 위의 결과와 상동

 

 

다음은 작성한 Controller 예제 코드. (html 코드는 생략)

package folaSmile.spring02.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;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {

        model.addAttribute("data", "Data from hello controller");
        return "hello";

    }

    //@RequestParam 의 옵션 required = false         -> 8080/hello-mvc -> 페이지가 로드됨
    //                               true(default) -> 8080/hello-mvc -> 로드되지 않음 (Whitelabel Error Page)
    //                                             -> 8080/hello-mvc?name=fola -> 페이지가 로드됨
    //                                             -> 8080/hello-mvc?name      -> 페이지가 로드됨
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name", required = true) String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }


    @GetMapping("hello-string")
    @ResponseBody // html <body></body> 부분에 직접 넣어주겠다는 어노테이션
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }


    @GetMapping("hello-api")
    @ResponseBody
    public HelloClass helloApi(@RequestParam("name") String name) {
        HelloClass hello = new HelloClass();
        hello.setName(name);
        return hello;


    }

    static class HelloClass {

        private String name;

        public String getName() {
            return name;
        }

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

}

 

 

Reference

 

(인프런 강의) 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

댓글