본문 바로가기
스프링 공부/스프링 입문

3. 스프링 부트 api 만들기

반응형

@GetMapping("주소") -> GET방식에 주소 url에 접속했을때 아래에 코드가 실행됩니다.

@ResponsBody ->  스트링일 경우 StringConverter,  객체일 경우 jsonConverter

 

1. 스트링일 경우

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

    }

사이트에서 검색을 할때 url을 확인해보면 ?search="내용" 이런 것을 확인 할 수 있습니다. 이 역할을 수행하는 것이 바로 @RequestParam 입니다. 

return 값으로는 파라미터에 해당하는 "name"과 name 변수가 StringConverter 통해 보여지게 됩니다.

 

http://localhost:8080/hello-string?name=이름이다

 

1. 객체일 경우

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

    static class Hello {
        public String getName() {
            return name;
        }

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

        private String name;

    }

정적 hello 클래스에서 이름에 해당하는 getter와 setter를 만들어 준 뒤 hello-api 에 접속하게 되었을 때 헬로 클래스를 반환하도록 하였습니다.

http://localhost:8080/hello-api?name=이름이다

객체일 경우 자동으로 json 형식으로 만들어서 반환해줍니다.