Programing/Springboot

springboot form, ajax 데이터 타입별 Controller에서 받는 방법 @RequestParam, @RequestBody

리커니 2021. 11. 1.
반응형

springboot form, ajax 데이터 타입별 Controller에서 받는 방법 @RequestParam, @RequestBody

 

이번 포스팅에서는 springboot web project에서 form 과 ajax로

자주 사용되는 데이터타입을 전송하고 받는 방법을 정리해보도록 하겠습니다.

 

1. Form data request로 받기

 

[HTML]

<form action="sendForm.getRequest" method="post">
    <input type="text" name="id"/>
    <input type="password" name="pw"/>
    <input type="submit" value="전송"/>
</form>

[Controller - 받을 수는 있지만 Request로 받는 방식은 GET Method에서만 사용합니다.]

@RequestMapping(value="sendForm.getRequest", method=RequestMethod.POST)
public String getRequest(HttpServletRequest req) {
    System.out.println("sendForm.getRequest");
    System.out.println(req.getParameter("id"));
    System.out.println(req.getParameter("pw"));
    return "test";
}

 

2. Form data VO로 받기

 

[HTML]

<form action="sendForm.getVO" method="post">
    <input type="text" name="id"/>
    <input type="password" name="pw"/>
    <input type="submit" value="전송"/>
</form>

 

[Controller - VO 자동 매핑]

@RequestMapping(value="sendForm.getVO", method=RequestMethod.POST)
public String getVO(TestVO vo) {
    System.out.println("sendForm.getVO");
    System.out.println(vo.getId());
    System.out.println(vo.getPw());
    return "test";
}

 

3. Form data Map으로 받기

 

[HTML]

<form action="sendForm.getMap" method="post">
    <input type="text" name="id"/>
    <input type="password" name="pw"/>
    <input type="submit" value="전송"/>
</form>

 

[Controller - @RequestParam 사용]

@RequestMapping(value="sendForm.getMap", method=RequestMethod.POST)
public String getMap(@RequestParam Map<String, Object> map) {
    System.out.println("sendForm.getMap");
    System.out.println(map.get("id"));
    System.out.println(map.get("pw"));
    return "test";
}

 

4. Form data ArrayList로 받기

 

[HTML]

<form action="sendForm.getArray" method="post">
    <input type="text" name="name"/>
    <input type="password" name="name"/>
    <input type="submit" value="전송"/>
</form>

 

[Controller - @RequestParam 사용]

@RequestMapping(value="sendForm.getArray", method=RequestMethod.POST)
public String getArray(@RequestParam ArrayList<String> name) {
     System.out.println("sendForm.getArray");
    for(int i=0, n=name.size(); i<n; i++) {
        System.out.println(name.get(i));
    }
    return "test";
}

 

5. Ajax data VO로 받기

 

[HTML - 아래 모든 방식 공통]

<div>
    <input type="text" name="id" id="ajaxReqId"/>
    <input type="password" name="pw" id="ajaxReqPw"/>
    <input type="button" value="전송" id="ajaxReqBtn"/>
</div>
<script>
const ajaxVOBtn = document.getElementById("ajaxVOBtn");
ajaxVOBtn.addEventListener("click", function(){
    const param = {
        id : document.getElementById("ajaxVoId").value,
        pw : document.getElementById("ajaxVoPw").value
    }
    ajax("sendAjax.getVO", param);
});

/*아래 샘플 코드에서도 사용*/
const ajax = function(url, data){
    console.log("ajax", url, data);
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8;");
    xhr.responseType = "json";
    xhr.onload = function(e) {
        console.log(this, e);
    };
    xhr.send(JSON.stringify(data));
}
</script>

 

[Controller - @RequestBody 사용]

@RequestMapping(value="sendAjax.getVO", method=RequestMethod.POST)
public String sendAjaxGetVO(@RequestBody TestVO vo) {
    System.out.println("sendAjax.getVO");
    System.out.println(vo.getId());
    System.out.println(vo.getPw());
    return "test";
}

 

5. Ajax data Map으로 받기

 

[Controller - @RequestBody 사용]

@RequestMapping(value="sendAjax.getMap", method=RequestMethod.POST)
public String sendAjaxGetMap(@RequestBody Map<String, Object> map) {
    System.out.println("sendAjax.getMap");
    System.out.println(map.get("id"));
    System.out.println(map.get("pw"));
    return "test";
}

 

5. Ajax data Array로 받기

 

[Controller - @RequestBody 사용]

@RequestMapping(value="sendAjax.getArray", method=RequestMethod.POST)
public String sendAjaxGetArray(@RequestBody ArrayList<String> array) {
    System.out.println("sendAjax.getArray");
    for(int i=0, n=array.size(); i<n; i++) {
        System.out.println(array.get(i));
    }
    return "test";
}

 

전달된 객체를 Controller 에서 받기 위해서

Form 전송 시에는 RequestParam Annotation을,

ajax로 전송 시에는 RequestBody를 사용하는 것을 볼 수 있습니다.

 

RequestParam은 메소드의 매개변수가 웹 요청 매개변수에 바인딩 되어야 함을 정의합니다.

주로사용되는 속성에는 name, value, required, defaultValue가 있습니다.

RequestParam은 주로 GET Method 에서 활용합니다.

자세한 내용은 아래의 Link를 참고하세요.

 

Link : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

 

RequestParam (Spring Framework 5.3.12 API)

Whether the parameter is required. Defaults to true, leading to an exception being thrown if the parameter is missing in the request. Switch this to false if you prefer a null value if the parameter is not present in the request. Alternatively, provide a d

docs.spring.io

 

RequestBody HTTP 요청에 Body를 Java Object로 변환해주는 역할을 합니다. (직렬화)

RequestBody는 POST Method 에서 활용합니다.

 

직렬화란?

자바 직렬화란 자바 시스템 내부에서 사용되는 객체 또는 데이터를 외부의 자바 시스템에서도 사용할 수 있도록 바이트(byte) 형태로 데이터 변환하는 기술과 바이트로 변환된 데이터를 다시 객체로 변환하는 기술(역직렬화)을 아울러서 이야기합니다.

자세한 내용은 아래의 Link를 참고하세요.

 

Link : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html

 

RequestBody (Spring Framework 5.3.12 API)

Whether body content is required. Default is true, leading to an exception thrown in case there is no body content. Switch this to false if you prefer null to be passed when the body content is null.

docs.spring.io

 

 

 

 

 

 

반응형

댓글

💲 추천 글