[Spring] HTTP 요청과 응답 방법

BE/Spring 2024. 7. 1.

 

-- 목차 --

  • HTTP 요청 파라미터
    • 쿼리 파라미터
    • 조회방법
    • 필수여부
    • 기본값 설정
  • HTTP 요청 메시지
    • JSON
  • HTTP 응답
    • JSON

 

 

 

HTTP 요청 파라미터

 

쿼리 파라미터

 

예시 URL ->

http://localhost:8080/request-param?id=west&age=20

 

GET 쿼리 파라미터와 POST HTML Form 전송 방식에서 사용이 가능하다.

 

 

조회방법

@RequestParam 애노테이션으로 사용가능

 

    @ResponseBody
    @RequestMapping("/request-param")
    public String requestParam(
            @RequestParam String id,
            @RequestParam Integer age
    ){
        log.info("id={}, age={}", id, age);

        return "ok";
    }

 

자동 형변환 해주어 바로 사용 가능하다. 

@RequestParam String username

@RequestParam Integer age

 

 

필수여부

 

@RequestParam(required = false) 으로 필수 여부 설정 가능하다.

@RequestParam(required = false) String id,
@RequestParam(required = false) Integer age

 

만약 해당 변수이름으로 값이 들어오지 않는다면 해당 변수에 NULL 을 할당한다.

int가 아닌 Integer 로 하는 이유는 NULL 을 할당할 수 있기 때문이다.

 

주의 할 점은 http://localhost:8080/request-param?id=&age=

위와 같이 값이 할당되지 않더라도 해당 변수에는 값일 들어온 것으로 간주하여 빈칸으로 할당한다.

 

 

기본값 설정

 

@RequestParam(defaultValue = "데이터") 로 기본값 설정 가능

@RequestParam(defaultValue = "Guest") String id,
@RequestParam(defaultValue = "-1") int age

 

 

 

 

기본값을 설정할 수 있다.

 

 

 

HTTP 요청 메시지

 

JSON 으로 데이터가 Body에 들어왔을 때는 다음과 같이 사용한다.

    @ResponseBody
    @PostMapping("/request-json")
    public String requestJson(@RequestBody BodyData bodyData) {

        log.info("id: {}, age: {}", bodyData.getId(), bodyData.getAge());
        
        return "ok"; 
    }

 

 

 

주의할 점:

 

@RequestBody 를 사용하면 HTTP 메시지 바디 정보를 조회할 수 있다. 헤더가 필요하다면 HttpEntity 혹은 @RequestHeader 를 사용하면 된다.

이렇게 HTTP 메시지 바디를 조회하는 기능은 요청 파라미터를 조회하는 @RequestParam 과는 아무 관련도 없다는 것을 기억해야 한다.

 

 

 

HTTP 응답 

 

JSON을 응답으로 주는 방법:

    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @GetMapping("/response")
    public Student responseJson() {
        Student student = new Student();
        student.setUsername("daniel");
        student.setAge(18);
        return student;
    }

 

@ResponseBody 애노테이션을 사용해서 바로 객체를 반환하면 된다.

이렇게 하면 상태코드를 지정해 줄 수 없으므로, @ResponseStatus(상태코드)를 통해서 상태코드를 지정해 줄 수 있다.