📌 동기
- html ➡️ controller *from, a(태그)
- controller ➡️ html *RequestParm, model.addatribute( )
📌 비동기(fatch)
- javascript ➡️ controller
- controller ➡️ javascript *map
1. vo 커맨드 객체 사용
- 데이터 하나만 가져올 수는 없음
2. Map 사용
- Javascript에서 가져올 데이터 : 'id'(key) : 'java'(value)
- 따라서 자료형 (@RequestBody HashMap<String, String> data)
- 가져오는 데이터가 복잡할 수록 map 사용
3. 배열 데이터 List
- 자바스크립트에서 배열이 넘어오면 ArrayList 로 받을 수 있음
4. 복잡한 데이터 전달받기
- List / Map 사용
ㅤ
1. @RequestParam
- url에 데이터가 함께 넘어올 때 사용
ex) localhost:8081/aaa?a=b- form, a 태그를 사용
- 사용은 편리하나, 복잡한 데이터를 받아올 수 없음
2. @RequestBody
- url이 아닌 body 영역에 데이터가 담겨서 올 때 사용
- 비동기 통신 시 @RequestBody 사용!
@Controller
@RequestMapping("/fetch")
public class FetchController {
@GetMapping("/main")
public String main(){
return "test/fetch/main";
}
비동기 통신으로 데이터 받기 ① vo 커맨드 객체
➡️ 데이터 하나만 가져올 수는 없음
@ResponseBody
@PostMapping("/fetch1")
public void fetch1(@RequestBody MemberVO memberVO){
System.out.println("fetch1 메서드 실행!");
System.out.println(memberVO);
}
비동기 통신으로 데이터 받기 ② Map
- Javascript에서 가져올 데이터 : 'id' : 'java'
- ///////////////////////////////// (key) (value)
➡️ 따라서 자료형 (@RequestBody HashMap<String, String> data)- 가져오는 데이터가 복잡할 수록 map 사용
- data에서 value값 가져오기(넘어오는 이름이 key가 됨): data.get()
@ResponseBody
@PostMapping("/fetch2")
public void fetch2(@RequestBody HashMap<String, String> data){
System.out.println("fetch2 메서드 실행!");
System.out.println(data);
//data에서 value값 가져오기(넘어오는 이름이 key가 됨): data.get()
System.out.println(data.get("id"));
System.out.println(data.get("name"));
System.out.println(data.get("age"));
}
비동기 통신으로 데이터 받기 ③ List
- 자바스크립트에서 배열이 넘어오면 ArrayList 로 받을 수 있음
@ResponseBody
@PostMapping("/fetch3")
public void fetch3(@RequestBody ArrayList<MemberVO> list){
System.out.println("fetch2 메서드 실행!");
System.out.println(list);
}
비동기 통신으로 데이터 받기 ④ 복잡한 데이터 받기
@ResponseBody
@PostMapping("/fetch4")
public void fetch4(@RequestBody HashMap<String, Object> map){
System.out.println("fetch4 메서드 실행!");
System.out.println(map);
//1. cartCode 데이터 출력
Object cartCode = (int)map.get("cartCode");
System.out.println(cartCode);
//2. memberId 데이터 출력
HashMap<String, String> memberInfo = (HashMap<String, String>)map.get("memberInfo");
String memberId = memberInfo.get("memberId");
System.out.println(memberId);
//
//위아래 동일 - 인터페이스 개념
List<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
//
Map<String, String> map1 = new HashMap<>();
HashMap<String, String> map2 = new HashMap<>();
AdminService a1 = new AdminServiceImpl();
AdminServiceImpl a2 = new AdminServiceImpl();
}
}
ㅤ
function fetch1(){ fetch('/fetch/fetch1', { //요청경로 method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json; charset=UTF-8' }, //컨트롤러로 전달할 데이터 body: JSON.stringify({ // 데이터명 : 데이터값 'id' : 'java', 'name' : '홍', 'age' : 20 }) }) .then((response) => { return response.text(); //return response.json(); //나머지 경우에 사용 }) //fetch 통신 후 실행 영역 .then((data) => {//data -> controller에서 리턴되는 데이터! }) //fetch 통신 실패 시 실행 영역 .catch(err=>{ alert('fetch error!\nthen 구문에서 오류가 발생했습니다.\n콘솔창을 확인하세요!'); console.log(err); }); }
function fetch2(){ fetch('/fetch/fetch2', { //요청경로 method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json; charset=UTF-8' }, //컨트롤러로 전달할 데이터 body: JSON.stringify({ // 데이터명 : 데이터값 'id' : 'java', 'name' : '홍', 'age' : 20 }) }) .then((response) => { return response.text(); //return response.json(); //나머지 경우에 사용 }) //fetch 통신 후 실행 영역 .then((data) => {//data -> controller에서 리턴되는 데이터! }) //fetch 통신 실패 시 실행 영역 .catch(err=>{ alert('fetch error!\nthen 구문에서 오류가 발생했습니다.\n콘솔창을 확인하세요!'); console.log(err); }); }
function fetch3(){ //자바스크립트의 객체 // const member = { // 'name' : '홍', // 'age' : 20, // 'id' : 'java' // }; //console.log(member.name); //홍 //console.log(member.id); //java //member.age = 50; //자바스크립트의 객체 베열 const arr = []; for(let i = 1; i <= 5; i++){ const member = { 'name' : `홍_${i}`, 'age' : 20 + i, 'id' : `java_${i}` }; arr.push(member); } fetch('/fetch/fetch3', { //요청경로 method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json; charset=UTF-8' }, //컨트롤러로 전달할 데이터 body: JSON.stringify(arr) }) .then((response) => { return response.text(); //return response.json(); //나머지 경우에 사용 }) //fetch 통신 후 실행 영역 .then((data) => {//data -> controller에서 리턴되는 데이터! }) //fetch 통신 실패 시 실행 영역 .catch(err=>{ alert('fetch error!\nthen 구문에서 오류가 발생했습니다.\n콘솔창을 확인하세요!'); console.log(err); }); }
function fetch4(){ //자바스크립트의 복잡한 데이터 생성 const imgList = [ { 'imgName' : 'aaa.jpg', 'imgCode' : 3 }, { 'imgName' : 'bbb.jpg', 'imgCode' : 5 } ]; const cartInfo = { 'cartCode' : 1, 'memberInfo' : { 'memberId' : 'java', 'memberName' : '홍' }, 'itemInfo' : { 'itemCode' : 5, 'itemName' : '상품1', 'itemPrice' : 1000, 'imgList' : imgList } }; console.log(cartInfo.itemInfo.imgList[0].imgName); fetch('/fetch/fetch4', { //요청경로 method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json; charset=UTF-8' }, //컨트롤러로 전달할 데이터 body: JSON.stringify(cartInfo) }) .then((response) => { return response.text(); //return response.json(); //나머지 경우에 사용 }) //fetch 통신 후 실행 영역 .then((data) => {//data -> controller에서 리턴되는 데이터! }) //fetch 통신 실패 시 실행 영역 .catch(err=>{ alert('fetch error!\nthen 구문에서 오류가 발생했습니다.\n콘솔창을 확인하세요!'); console.log(err); }); }
ㅤ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ margin-bottom: 16px; } </style> </head> <body> <h3>Fetch를 통해 Javascript 데이터를 Controller에서 받기</h3> <div> <input type="button" value="vo객체로 데이터 전달받기" onclick="fetch1()"> </div> <div> <input type="button" value="Map을 사용해서 데이터 전달받기" onclick="fetch2()"> </div> <div> <input type="button" value="배열 데이터를 list로 받기" onclick="fetch3()"> </div> <div> <input type="button" value="복잡한 데이터 전달받기" onclick="fetch4()"> </div> <script src="/js/test/fetch.js"></script> </body> </html>