[Spring Boot] GET

노성빈·2024년 4월 30일

Spring Boot

목록 보기
1/6
post-thumbnail

📌 GET?

  • 서버로부터 정보를 요청할 때 사용된다.
  • URL의 쿼리 문자열에 데이터를 포함한다.


📌 예제

@RestController
@RequestMapping("/api")
public class RestApiController {

    @GetMapping(path = "/hello")
    public String hello() {
        var html = "<html> <body> <h1> Hello Spring Boot </h1> </body> </html>";
        return html;
    }

    // PathVariable 활용
    @GetMapping(path = "/echo/{message}/age/{age}/is-man/{isMan}")
    public String echo(
            @PathVariable(name = "message") String msg,
            @PathVariable int age,
            @PathVariable boolean isMan
    ) {
        System.out.println("echo message : " + msg);
        System.out.println("echo age : " + age);
        System.out.println("echo isMan : " + isMan);

        return msg.toUpperCase();
    }

    @GetMapping(path = "book")
    public void queryParam(
            @RequestParam String category,
            @RequestParam String issuedYear,
            @RequestParam(name = "issued-month") String issuedMonth,
            @RequestParam(name = "issued_day") String issuedDay
    ) {
        System.out.println(category);
        System.out.println(issuedYear);
        System.out.println(issuedMonth);
        System.out.println(issuedDay);
    }
    @GetMapping(path = "book2")
    public void queryParamDto(
            BookQueryParam bookQueryParam
    ) {
        System.out.println(bookQueryParam);
    }
}

✏️ @Restcontroller

  • Rest컨트롤러 클래스에 부여되는 어노테이션이다.
  • 해당 클래스가 RESTful 웹 서비스의 엔드 포인트를 처리하는 컨트롤러임을 나타낸다.
  • 해당 어노테이션을 사용하면 클래스의 모든 메서드가 HTTP 응답을 생성하게 된다.
  • 이 클래스는 단순 데이터를 반환하거나, Json, XML등의 형식으로 객체를 직렬화하여 반환할 수 있다.

✏️ @RequestMapping

괄호 안에 있는 주소로 시작하는 주소는 해당 컨트롤러로 받겠다는 내용을 설정한다.


✏️ @GetMapping

처리 할 주소를 정한다.



📌 GET 요청 방법

✏️ 문자열로 요청

문자열로 요청 받으면 해당 메서드의 결과를 return 해준다.

@GetMapping(path = "/hello")
    public String hello() {
        var html = "<html> <body> <h1> Hello Spring Boot </h1> </body> </html>";
        return html;
    }

✏️ @PathVariable

  • @Getmapping 에서 path를 선언할 때 {}에 변수명을 넣은 매개변수에 @ParhVariable에서 받아준다.
  • @GetMapping의 path에서 변수명과 매개변수의 이름이 같다면 바로 사용이 가능하다.
    _ @GetMapping의 Path에서 변수명과 매개변수의 이름이 다르다면 (name = " ")을 사용하여 매칭시켜준다.
@GetMapping(path = "/echo/{message}/age/{age}/is-man/{isMan}")
    public String echo(
            @PathVariable(name = "message") String msg,
            @PathVariable int age,
            @PathVariable boolean isMan
    ) {
        System.out.println("echo message : " + msg);
        System.out.println("echo age : " + age);
        System.out.println("echo isMan : " + isMan);

        return msg.toUpperCase();
    }

✏️ @RequestParam

  • Query Parameter로 받을 때 사용한다.
  • (name = " ") 을 통해 Query Parameter 에서 다른 변수명으로 들어오는 값을 받을 수 있다.
  • 값을 객체로 바로 받을 수 있다.
    ❗️ 값을 객체로 바로 받을 경우, Query Parameter에서 자바의 변수명과 맞춰서 요청해야 된다.

💡 Query Parameter

특정 정보의 필터링을 걸때 사용한다.
ex) https://www.foo.bar/book?category=IT&issuedYear=2023&issued-month=01&issued_day=31
'?'로 시작하고, 이어주는 형태는 '&'이다

@GetMapping(path = "book")
    public void queryParam(
            @RequestParam String category,
            @RequestParam String issuedYear,
            @RequestParam(name = "issued-month") String issuedMonth,
            @RequestParam(name = "issued_day") String issuedDay
    ) {
        System.out.println(category);
        System.out.println(issuedYear);
        System.out.println(issuedMonth);
        System.out.println(issuedDay);
    }
    
@GetMapping(path = "book2")
    public void queryParamDto(
            BookQueryParam bookQueryParam
    ) {
        System.out.println(bookQueryParam);
    }
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BookQueryParam {
    private String category;
    private String issuedYear;
    private String issuedMonth;
    private String issuedDay;
}

0개의 댓글