이것저것 해보기🌼

[REST API] GET 다루기 본문

BE/Spring Boot

[REST API] GET 다루기

realtree 2021. 6. 30. 14:56

GET Method를 사용하는 여러 방법

 

package com.example.hello.controller;

import com.example.hello.dto.UserRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/get")
public class GetApiController {

    //1. 기본 GET 사용방법
    @GetMapping(path = "/hello") //http://localhost:9090/api/hello
    public String getHello(){
        return "get Hello";
    }

    @RequestMapping(path = "/hi", method = RequestMethod.GET) //http://localhost:9090/api/get/hi
     public String  hi(){
        return "hi";
    }

    //2. Path Variable 사용하기
    //http://localhost:9090/api/get/path-variable/{name}
    @GetMapping("/path-variable/{name}")
    public String pathVariable(@PathVariable(name = "name") String pathName){
        System.out.println("PathVariable: " + pathName);
        return pathName;
    }

    //3. Query Parameter 사용하기
    //http://localhost:9090/api/get/query-param?user=seohee&email=seohee@gmail.com?age=26
    @GetMapping(path="query-param")
    public String queryParam(@RequestParam Map<String, String> queryParam){
        StringBuilder sb = new StringBuilder();

        queryParam.entrySet().forEach( entry -> {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");

            sb.append(entry.getKey()+" = " + entry.getValue()+"\n");
        });

        return sb.toString();
    }

    @GetMapping("query-param02")
    public String queryParam02(
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam int age
    ){
        System.out.println(name);
        System.out.println(email);
        System.out.println(age);
        return name+" "+email+" "+age;
    }

    @GetMapping("query-param03")
    public String queryParam03(UserRequest userRequest){ //@RequestParam Annotation 을 붙이지 않음
        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());
        return userRequest.toString();
    }
    
}

 

 

* Request 시 응답 확인

 

 

 

Query Parameter 넣기

 

 

'BE > Spring Boot' 카테고리의 다른 글

[REST API] PUT 다루기  (0) 2021.06.30
[REST API] POST 다루기  (0) 2021.06.30
웹 개발 개론  (0) 2021.06.30
TO-DO LIST 만들기 프로젝트 2 (실행 및 테스트)  (0) 2021.06.29
TO-DO LIST 만들기 프로젝트 1 (구현)  (0) 2021.06.28