ABAP DUMP ERROR 24시

스프링 서버에서 요청 데이터 만들기 본문

[WEB]Back-end/Spring MVC

스프링 서버에서 요청 데이터 만들기

이운형 2022. 2. 16. 19:28
반응형

# 인프런 김영한의 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 개인적으로 정리한 글입니다.

 

Q . 스프링 서버에서  요청 데이터 만들기

 

대표적인 요청 3가지는 GET 쿼리 파라미터 , POST-HTML FORM 방식 그리고 HTTP API 방식이 존재한다.

Q. 그래서 내가 해깔리는게 뭐야? 한방정리.

 

요청 파라미터 방식을 사용하는 것은  

GET 쿼리 파라미터 , POST-HTML FORM 방식

@RequestParam , @ModelAttribute를 사용한다.

 

HTTP MESSAGE BODY를 통해 데이터가 넘어오는 방식은

HTTP API 방식

@RequestBody를 사용한다. -주로 이거 사용 (JSON을 반환해줌)

 

1. 요청 파라미터 방식 예시

@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(
        @RequestParam("username") String username,
        @RequestParam("age") int age){

    log.info("username = {}, age={}",username,age);
    return "OK";
@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
        @RequestParam(required = true) String username, // required =true 하면 필수로 username을 가져와야 한다. 없으면 400 오류 발생
        @RequestParam(required = false) Integer age){
    log.info("username = {}, age={}",username,age);
    return "OK";
    // 기본형 int 에서는 null 이 사용 금지 ,, 객체형인 Integer 에는 null이 사용 가능하다. 500 오류 발생
}
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(
        @ModelAttribute HelloData helloData){ // helloProperties 를 찾는다 properties 는 getter , setter와 같은 애들

    log.info("username = {} ,age = {}", helloData.getUsername() ,helloData.getAge());
    return helloData.getUsername() +"님 안녕하세요";
}

2. HTTP MESSAGE BODY를 통해 데이터가 넘어오는 방식

@ResponseBody
@PostMapping("request-body-string-v4")
public String responseBodyStringV4(@RequestBody String messageBody){ //@RequestBody를 사용하면 Http MessageBody 정보를 편리하게 조회할수 있다.
    // 파라미터로 가져오는 @RequestParam 혹은 @ModelAttribute 와는 관계없이  그냥 Body내용만 콱 잡아서 온다.
    log.info("messageBody={}", messageBody);

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

 

반응형
Comments