REST API - GET

강9·2024년 1월 5일
0

Web

목록 보기
3/7
post-thumbnail

🔖 GET

📌 Method

의미CRUD멱등성안정성Path VariableQuery ParameterDataBody
GET리소스 취득ROOOOX

💡 멱등성이란? : 서버에 여러번 요청해도 항상 결과가 같다의 표현
💡 △ 표시 : 할 수는 있지만 하지 않는 것을 추천하는 것을 △로 표시함


📌 어노테이션

@RestController : 컨트롤러 기능을 하는 특정 클래스를 지정
@RequestMapping("/주소A") : 해당 주소 처리
@GetMapping(path = "/주소B") : 해당 클래스 안에 해당된 /주소A 하위에 /주소B 메서드를 처리

@RestController
@RequestMapping("/api") // http://localhost:8080/api
public class RestApiController {

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

💡 PATH Variable이란?

주소 내에 정보를 전달하는 방법

https://www.foo.bar/user-id/100
https://www.foo.bar/user-id/100/card-id/200

  • 특정한 리소스의 정보를 가져올 때 사용
  • 유동적으로 변할 수 있는 부분 100, 200
  • 단점 : 주소가 노출되기 때문에 주소에 대한 값을 변경해볼 수 있기 때문에 보안에 항상 대비해야함(조회 권한 등)
  • path를 {} 중괄호로 표기 :
@GetMapping(path = "/echo/{message}")
@PathVariable String message
@GetMapping(path = "/echo/{message}") // http://localhost:8080/api/echo/입력할 메세지
    public String echo(
            @PathVariable String message
    ) {
        System.out.println("echo message : " + message);

        return message;
    }
//  지정한 Path Variable 이름을 변환하여 호출할 경우
    @GetMapping(path = "/echo/{message}") // http://localhost:8080/api/echo/입력할 메세지
    public String echo(
            @PathVariable(name = "message") String msg
    ) {
        System.out.println("echo message : " + msg);        

        return msg;
    }

💡 한글이 깨질 경우

IntelliJ를 UTF-8로 인코딩 설정

설정 -> 에디터 -> 파일 인코딩
Setting -> Editor -> File Encodings

  • 전역 인코딩 : UTF-8 (Global Encoding)
  • 프로젝트 인코딩 : UTF-8 (Project Encoding)
  • 프로퍼티 파일 인코딩 : UTF-8 (default encoding for properties files)
    으로 설정 후 IntelliJ 재실행

💡 Console에서 한글이 깨질 경우

설정 -> 에디터 -> 일반 -> 콘솔
Setting -> Editor -> General -> Console

  • 디폴트 인코딩 : UTF-8 (Default Encoding)
    으로 설정 후 IntelliJ 재실행


💡 8080 port값이 중복되어 실행 오류가 날 때

  1. 기존 실행중인 서버 닫고 다시 실행

  2. (Windows 기준)터미널 -> netstat -ano | findstr 8080 -> LISTENING값 확인
    taskkill /f /pid LISTENING값 입력


💡 Query Parameter이란?

특정 정보의 필터링을 걸 때 사용한다.

?로 시작하고, 이어주는 형태는 &로 묶어준다.

1️⃣ 수동으로 파싱하는 방법

// 수동으로 파싱하는 방법
 @GetMapping(path = "/book") // http://localhost:8080/api/book?category=IT&issuedYear=2023&issued-month=01&issued_day=31
    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);

    }

2️⃣ 객체(DTO)를 사용하여 파싱하는 방법

// DTO(객체)를 사용하여 파싱하는 방법
 @GetMapping(path = "/book2") // http://localhost:8080/api/book2?category=IT&issuedYear=2023&issuedMonth=01&issuedDay=31
    public void queryParamDto(
            BookQueryParam bookQueryParam
    ) {
        System.out.println(bookQueryParam);
}

// 별도 DTO 클래스 생성
@Data // 롬복 (get,set,toString 등 자동 생성)
@AllArgsConstructor // 전체 파라미터를 가진 생성자
@NoArgsConstructor // 기본 생성자
public class BookQueryParam {
    private String category;
    private String issuedYear;
    private String issuedMonth;
    private String issuedDay;

}
profile
코린이 일기

0개의 댓글

관련 채용 정보