Programming/Web-Spring

[SpringBoot] html페이지에서 Json 값을 객체로 받아올때 주의사항

아이바 2023. 6. 14. 17:43

model 

public class Star {
String name;
int age;

public Star(String name, int age) {
this.name = name;
this.age = age;
}
}

 

 

 

 

controller 

// [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
// Content type: application/json
// Body
// {"name":"Robbie","age":"95"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}

 

 

 

 

html 

 

<h2>POST /hello/request/form/json</h2>
<form id="helloJsonForm">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
</form>
<div>
<button id="helloJsonSend">전송</button>
</div>
<div>
<div id="helloJsonResult"></div>
</div>

script 

 

<script>
// GET /star/{name}/age/{age}
const helloPathForm = document.querySelector("#helloPathFormSend")
helloPathForm.onclick = (e) => {
const form = document.querySelector("#helloPathForm");
const name = form.querySelector('input[name="name"]').value;
const age = form.querySelector('input[name="age"]').value;
const relativeUrl = `/hello/request/star/${name}/age/${age}`;
window.location.href = relativeUrl;
}

// POST /hello/request/form/json
const helloJson = document.querySelector("#helloJsonSend")
helloJson.onclick = async (e) => {
const form = document.querySelector("#helloJsonForm");

const data = {
name: form.querySelector('input[name="name"]').value,
age: form.querySelector('input[name="age"]').value
}

const response = await fetch('/hello/request/form/json', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})

const text = await response.text(); // read response body as text
document.querySelector("#helloJsonResult").innerHTML = text;
};
</script>

 

ResponseBody 를 통해 

 

json으로 데이터를 받을때 

 

 

컨트롤러에서 받는 json파라미터에 @RequestBody를 선언하고 

json 키값에 부합하는 클래스(Star)를 생성해서 사용해야함 

 

 

728x90