[Spring] HTTP 응답, 요청 관련 Annotation

Woo0·2023년 10월 30일
post-thumbnail

HTTP 요청

  • GET 쿼리 파라미터: @ModelAttribute @RequestParam
  • POST HTML Form: @ModelAttribute @RequestParam
  • HTTP 메시지 바디: @RequestBody

HTTP 응답

  • 정적 리소스
  • 뷰 템플릿
  • HTTP 메시지 사용: @ResponseBody

@Data
public class HelloData {
	private String username;
	private int age;
}

개발을 하면 요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 값을 넣어주어야 한다.

📝 @ModelAttribute

요청: /request-param?username=wooo&age=22

@ResponseBody
@RequestMapping("/model-attribute")
public String modelAttributeV(@ModelAttribute HelloData helloData) {

	log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
 	return "ok";
}

스프링 MVC는 @ModelAttribute가 있으면 우선 HelloData 객체를 생성한다. 요청 파라미터의 이름으로 HelloData 객체의 프로퍼티(username, age)를 찾고 해당 프로퍼티의 setter를 호출해서 파라미터의 값을 입력한다.

📝 @RequestParam

요청: /request-param?username=wooo&age=22

@ResponseBody
@RequestMapping("/request-param")
public String requestParam(@RequestParam("username") String memberName, 
		@RequestParam("age") int memberAge) {

        log.info("username={}, age={}", memberName, memberAge);
        return "ok";
    }

@RequestParam이 있으면 명확하게 요청 파리미터에서 데이터를 읽을 수 있고
required, defaultValue 옵션을 설정할 수 있다.

📝 @RequestBody

@Slf4j
@Controller
public class RequestBodyController {

    @ResponseBody
    @PostMapping("/request-body-string")
    public String requestBodyString(@RequestBody String messageBody) throws IOException {    // 최종

        log.info("messageBody={}", messageBody);
        return "ok";
    }

    @ResponseBody 
    @PostMapping("/request-body-json")
    public HelloData requestBodyJson(@RequestBody HelloData data) { 
    
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        return data;
    }
}

@RequestBody를 사용하면 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다. 헤더 정보가 필요하다면 HttpEntity를 사용하거나 @RequestHeader를 사용하면 된다. 이렇게 메시지 바디를 직접 조회하는 기능은 요청 파라미터를 조회하는 @RequestParam, @ModelAttribute와는 관계가 없다.

📝 @ResponseBody

@ResponseBody를 사용하면 view를 사용하지 않고 응답 결과를 HTTP 메시지 바디에 직접 담아서 전달할 수 있다. @ResponseBody가 없으면 뷰 리졸버가 실행되어서 뷰를 찾고 렌더링한다.

@RestController = @Controller + @ResponseBody


출처: 스프링 MVC 1편 (김영한)

profile
실패를 두려워하지 않는 백엔드 개발자가 되기 위해 노력하고 있습니다.

0개의 댓글