fetch

  • JavaScript 내장 API
  • 리소스를 비동기 요청할 수 있다
  • 사용 형식
let promise = fetch(url, [options])
  • options
    선택 매개변수, method나 header 등을 지정할 수 있음
    options에 아무것도 넘기지 않으면 요청을 GET메서드로 진행됨
  • 콜백함수가 호출되면서 response객체 타입을 데이터로 받음
  • response메서드
    • status
             HTTP  상태 코드
    • ok
             boolean 값
             HTTP 상태 코드가 200과 299 사이일 경우 true
    • text()
             받은 url을 text로 받음
    • json()
             받은 url을 json형태로 받음
              (JSON.parse(text변수)와 같음)
  • fetch는 error를 reject하지 않고
          대신 ok상태가 false인 resolve가 반환
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<style>
.res{
display: flex;
}
.res div{
box-sizing : border-box;
flex : 25%;
}
</style>
<script>
window.onload= function(){
$('#text').on('click', function(){
fetch('text.jsp')
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.text(); // 결과를 text로 받음
})
.then(function(data){
//data는 결과를 text로 받은 변수
console.log("data", data);
let arr = data.split("/");
console.log(arr);
res = `<ul>`;
for(i=0; i<arr.length;i++){
res+=`<li>${arr[i]}</li>`;
}
res += `</ul>`;
$('#result1').html(res);
})
})
$('#obj').on('click', function(){
fetch('jobj.jsp')
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.json(); // 결과를 json으로 받음
})
.then(function(data){
//data는 결과를 text로 받은 변수
console.log("data", data);
let str = `<p>이름 : ${data.name} </p>
<p>주소 : ${data.addr}</p>
<p>전화번호 : ${data.tel}</p><hr color="gray">`;
$('#result2').html(str);
})
})
$('#arr').on('click', function(){
fetch('jsonarr.jsp')
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.json(); // 결과를 json으로 받음
})
.then(function(data){
//data는 결과를 text로 받은 변수
console.log("data", data);
res = `<ol>`;
for(i=0; i<data.length;i++){
res+=`<li>${data[i]}</li>`;
}
res += `</ol>`;
$('#result3').html(res);
})
})
$('#objarr').on('click', function(){
fetch('jobarr.jsp')
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.json(); // 결과를 json으로 받음
})
.then(function(data){
//data는 결과를 text로 받은 변수
console.log("data", data);
let str = "";
$.each(data, function(){
str += `<p>이름 : ${this.name} </p>
<p>주소 : ${this.addr}</p>
<p>전화번호 : ${this.tel}</p><hr color="gray">`;
})
$('#result4').html(str);
})
})
}
</script>
</head>
<body>
<div class="box">
<h3></h3>
<input type="button" value="text" id="text">
<input type="button" value="obj" id="obj">
<input type="button" value="arr" id="arr">
<input type="button" value="objarr" id="objarr">
<br> <br>
<div class="res">
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<div id="result4"></div>
</div>
</div>
</body>
</html>

promise의 resolve와 reject로 처리하는 예제 참고

XMLRequest / promise fetch
function getData(url){
   const xhr = new XMLHttpRequest();
   return new Promise((resolve, reject) => {
   xhr.open("GET", url);
   xhr.onload = () => resolve(xhr.responseText);
   xhr.onerror = () => reject(new Error("오류가 발생했어요"));
   xhr.send();
   })
}

getData('text.jsp')
.then((text)=>{
})
fetch('text.jsp')
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.text(); // 결과를 text로 받음
})
.then(function(data){
//data는 결과를 text로 받은 변수

})
resolve에서
responseText로 text로 return
ok로 오류 발생확인 후 오류가 없다면
text()메서드로 text을 return

직렬화

직렬화하지않은 형식

fetch("jsp나 서블릿",{
method : "POST",
headers : {
"Content-type" : "application/x-www-form-urlencoded"
},
body : "id="+vid+"&name="+vname+"&email="+vemail
})
받아올 때 데이터
request객체.getParameter()

☆ json 직렬화 ☆

fetch("jsp나 서블릿",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8"
},
body : JSON.stringify({id : vid, name : vname, email : vemail}) // json 형식으로 작성 VO이름과 동일
})
받아올때 데이터
request.setCharacterEncoding("utf-8");
StringBuffer buf = new StringBuffer();
String line = null;
try {
BufferedReader br = request.getReader();
while((line = br.readLine())!=null) {
buf.append(line);
}
} catch (Exception e) {
// TODO: handle exception
}
String reqdata = buf.toString();
Gson gson = new Gson();
ZipVO vo = gson.fromJson(reqdata, ZipVO.class);
  • 객체를 저장 가능한 상태(디스크에 파일 형태 등)
  • 혹은 전송 가능한 상태(네트워크 상의 데이터 스트림 형태)로 변환하는 것을 뜻함
  • 응용 프로그램에서 쓰는 데이터를 네트워크를 통해 전송하거나 
    DB 또는 파일에 저장 가능한 형식으로 바꾸는 프로세스다. 
  • 역직렬화는 외부 소스에서 데이터를 읽고 이를 런타임 객체로 바꾸는 반대 프로세스
    역직렬화 : 직렬화된 파일 등을 역으로 직렬화하여 다시 객체의 형태로 만드는 것을 의미한다.
                       저장된 파일을 읽거나 전송된 스트림 데이터를 읽어 원래 객체의 형태로 복원한다.
직렬화( serialize ) 역직렬화( Deserialize )
자바 언어에서 사용되는 Object 또는 Data를 다른 컴퓨터의 자바 시스템에서도 사용 할수 있도록
바이트 스트림(stream of bytes) 형태로 연속적인(serial) 데이터로 변환하는 포맷 변환 기술을 일컫는다. 
바이트로 변환된 데이터를 원래대로 자바 시스템의 
Object 또는 Data로 변환하는 기술이다.
  • 데이터 직렬화 포맷
    CSV, XML, JSON 형태의 직렬화
    • CSV (comma-separated values)
      몇 가지 필드를 쉼표(,)로 구분한 텍스트 데이터 및 텍스트 파일이다. 
      텍스트와 숫자를 CSV 파일에 저장하면 프로그램 간에 이동하기가 쉽다.
      확장자는 .csv이며 MIME 형식은 text/csv이다. 
      오래전부터 스프레드시트나 데이터베이스 소프트웨어에서 많이 쓰였음
    • JSON
      Java 객체를 JSON표현식으로 변환하는 API - 직렬화  - Gson.toJSON(obj)
      JSON 표현식 형태의 스트링을 Java 객체로 변환 또한 가능하다 -역직렬화 - Gson.fromJSON(str, typeclass)
      JSON.stringify(object) : script형태의 객체를 json문자열로 변환 (직렬화)
      JSON.parse(str) : json형태의 문자열을 javascript객체로 변환(역직렬화)
    • GSON
      Google에서 제공하는 Java라이브러리로 Java객체와 json간의 직렬화 및 역직렬화를 지원
      주로 사용할 클래스는 Gson 이고 그냥 new Gson() 으로 객체생성하면 된다.
      GsonBuilder 클래스는 다양한 셋팅을 해서 Gson 객체를 생성할 때 사용한다. 
기본객체  :
Gson gson = new Gson();
(json 형태를 한 줄로 출력)

Gson gson = new GsonBuilder().create();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
(json 형태를 보기 좋게 출력하는 것)

예제

html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
const createFn = () =>{
let vid = $('#id').val();
let vname = $('#name').val();
let vemail = $('#email').val();
fetch("params.jsp",{
method : "POST",
headers : {
"Content-type" : "application/x-www-form-urlencoded" // 직렬화X
},
body : "id="+vid+"&name="+vname+"&email="+vemail
})
.then(function(resp){
console.log(resp)
if(resp.ok) return resp.json();
else throw new Error(resp.statusText)
})
.then(function(data){
res = `아이디 : ${data.id}<br>
이름 : ${data.name}<br>
메일 : ${data.email}`;
$('#result1').html(res);
})
}
// 직렬화하여 전송하는 함수
// JSON.stringify() : 자바스크립트 객체를 json문자열로 직렬화
const createFnSeri = () =>{
let vid = $('#id').val();
let vname = $('#name').val();
let vemail = $('#email').val();
fetch("paramseri.jsp",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8" // json 직렬화
},
body : JSON.stringify({id : vid, name : vname, email : vemail}) // json
})
.then(function(resp){
console.log(resp)
if(resp.ok) return resp.json();
else throw new Error(resp.statusText)
})
.then(function(data){
res = `아이디 : ${data.id}<br>
이름 : ${data.name}<br>
메일 : ${data.email}`;
$('#result2').html(res);
})
}
$(function(){
// 파라미터 전송
$('#send').on('click',createFn);
// 직렬화 전송
$('#serisend').on('click',createFnSeri);
$('#btn').on('click',createFn1);
})
</script>
</head>
<body>
<div class="box">
<h3></h3>
<form>
<input placeholder="아이디" name="id" id="id"><br>
<input placeholder="이름" name="name" id="name"><br>
<input placeholder="이메일" name="email" id="email"><br>
<input type="button" value="전송" id="send">
<input type="button" value="직렬화전송" id="serisend">
</form>
<br> <br>
<input type="button" value="전송" id="btn">
<div id="result1"></div>
<div id="result2"></div>
</div>
</body>
</html>

parameseri.jsp

<%@page import="kr.or.ddit.vo.ParamsVO"%>
<%@page import="com.google.gson.Gson"%>
<%@page import="java.io.BufferedReader"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
직렬화 된 데이터 - 한 덩어리의 json문자열
{id : " ", name : " ", email : " "}
*/
StringBuffer strbuf = new StringBuffer();
String line = null;
try{
BufferedReader reader = request.getReader();
while( (line = reader.readLine()) !=null){
strbuf.append(line);
}
}catch(Exception e){
}
String reqdata = strbuf.toString();
// 역직렬화 - json문자열객체를 - 자바 객체로 변환 (id, name, email을 포함하고 있는 VO 객체)
Gson gson = new Gson();
ParamsVO vo = gson.fromJson(reqdata, ParamsVO.class);
%>
{
"id" : "<%=vo.getId() %>",
"name" : "<%=vo.getName() %>",
"email" : "<%=vo.getEmail() %>"
}

ParamsVO

더보기
package kr.or.ddit.vo;
public class ParamsVO {
private String id;
private String name;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

직렬화 하지않은 jsp

getParameter로 데이터를 가져옴

post일 땐 한글이 깨지므로 setCharacterEncoding()으로 인코딩 설정 필요

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String userId = request.getParameter("id");
String userName = request.getParameter("name");
String userMail = request.getParameter("email");
// db 를 이용한 crud 처리
// 처리한 결과값을 가지고 응답데이터를 생성한다
%>
{
"id" : "<%=userId %>",
"name" : "<%=userName %>",
"email" : "<%=userMail %>"
}

직렬화 jsp

  1. 한 덩어리의 문자열을 StringBuffer로 받음
    StringBuffer 클래스의 인스턴스는 값을 수정하거나, 추가할 수 있다.
  2. 데이터를 가져오는 방법은
    • getReader()로 BufferedReader를 이용
    • getInputStream()로 BufferedInputStream를 이용
  3. 한 줄에 해당하는 데이터를 가져오므로 readLine()을 통해 꺼내며 그 꺼낸 데이터를 StringBuffer에 append()한다
  4. append한 StringBuffer는 toString()으로 String 한 값을 가져올 수 있다.
    >> 이때 String은 json문자열로 저장된다
  5. Gson 객체를 생성해서
    자바 객체(VO)로 변환시킨다
    Gson객체.fromJson(json문자열, VO클래스.class)

fetch와 gson을 이용한 member테이블

이전에 만든 member테이블

html(fetch)

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<style>
.res{
display: flex;
}
.res div{
box-sizing : border-box;
flex : 25%;
}
</style>
<script>
$(function() {
$('#member').on('click', function(){
// /를 안쓰면 404 오류
getMember('/Jqpro/MemberList.do')
.then((data)=>{
res = JSON.parse(data);
return res;
})
.then((data)=>{
let code=`<table class="table"><tr>
<th>아이디</th>
<th>이름</th>
<th>이메일</th>
<th>전화번호</th>
</tr>`;
$.each(res, function(){
code += `<tr><td>${this.mem_id} </td>
<td>${this.mem_name}</td>
<td>${this.mem_mail}</td>
<td>${this.mem_hp}</td></tr>`;
})
code+=`</table>`;
$('#result1').html(code);
})
})
})
function getMember(url){
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(new Error("오류가 발생했어요"));
xhr.send();
})
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<body>
<div class="box">
<h3></h3>
<input type="button" value="memberList" id="member">
<br> <br>
<form action="">
<input type="submit">
</form>
<div id="result1"></div>
</div>
</body>
</html>

jsp(gson)

toJson()메서드
>> json형식으로 String형태로 반환

반환된 String을 print()로 보낸후 flush()를 사용할 것

<%@page import="com.google.gson.GsonBuilder"%>
<%@page import="com.google.gson.Gson"%>
<%@page import="kr.or.ddit.member.vo.MemberVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// Java 객체를 JSON표현식으로 변환하는 API - 직렬화 - Gson.toJSON(obj)
// 변수를 지정해서 json을 만들 수 없고 전체 출력된다
List<MemberVO> list = (List<MemberVO>)request.getAttribute("listvalue");
// json이 한줄로 출력됨 (Network>Response)
// Gson gson = new Gson();
// json이 보기 좋게 출력됨
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(list);
// out이 내장 객체이므로 생성 안해줘도 됨
out.print(json);
out.flush();
%>

 

'웹프로그래밍 > jQuery' 카테고리의 다른 글

[jQuery] 게시판  (2) 2024.06.03
[jQuery] 회원가입페이지 만들기★ , serialize  (0) 2024.05.31
[jQuery] Servlet을 활용한 promise  (0) 2024.05.28
[jQuery] 비동기 AJAX (json)  (0) 2024.05.27
[jQurey] 비동기 AJAX  (0) 2024.05.24