728x90
★ 실제 AJAX 구현
- 1. 순수 자바스크립트(원래 Ajax)
- 2. jQuery Ajax (가장 많이 사용)
- 3. ES6 > Promise, await
■ 서버 페이지(Servlet/JSP)를 만들 때
- 1. 브라우저로 요청할 페이지?
- 2. Ajax로 요청할 페이지?
■ 1. 순수 자바스크립트(원래 Ajax)
- 필요 파일
- 페이지 > 보임
- com.test.ajax > "Ex05.java"
- com.test.ajax > "Ex05Data.java"
- 데이터(처리) > 안보임
- views > "ex05.jsp"
- views > "ex05data.jsp"
- webapp > "ex05.txt"
■ 1. 소스 코드
- Ex05.java
package com.test.ajax;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex05.do")
public class Ex05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex05.java
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex05.jsp");
dispatcher.forward(req, resp);
}
}
- ex05.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body class="narrow">
<h1>Ajax 요청</h1>
<div>
<input type="button" value="확인" id="btn1">
<hr>
<div id="div1"></div>
</div>
<hr>
<div>
<input type="text" id="txt2">
<input type="button" value="전송" id="btn2">
<hr>
<div id="div1"></div>
</div>
<hr>
<div>
다른 작업 : <input type="text">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$('#btn1').click( () => {
const ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
//요청한 데이터를 올바르게 수신할 수 있는 순간!!
$('#div1').text(ajax.responseText);
alert(ajax.responseText);
}
};
// ajax.open('GET', '/ajax/ex05.txt');
ajax.open('GET', '/ajax/ex05data.do');
ajax.send(); //연결 + 접속 + 요청
});
$('#btn2').click( ()=> {
const ajax = new XMLHttpRequest();
//ajax > (데이터) > 서버
//1. GET > QueryString
//2. POST
ajax.open('GET', '/ajax/ex05data.do?txt2=' + $('#txt2').val());
ajax.send();
});
</script>
</body>
</html>
- Ex05Data.java
package com.test.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex05data.do")
public class Ex05Data extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex05Data.java
//System.out.println("서블릿 호출됨.");
//Ajax 응답
//- JSP 페이지 < (더편함) < PrintWriter
//PrintWriter writer = resp.getWriter();
//writer.write("200");
//writer.close();
// RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex05data.jsp");
// dispatcher.forward(req, resp);
String txt2 = req.getParameter("txt2");
System.out.println("GET : " + txt2);
}
}
- ex05data.jsp : Ajax에서는 좋지 않은 예
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>200
■ 실행 결과
- 데이터 받기
- 데이터 전송
■ 2. jQuery Ajax (가장 많이 사용)
- 필요 파일들
- com.test.ajax > "Ex06.java"
- views > "ex06.jsp"
- com.test.ajax > "Ex06Data.java"
■ 2. 소스코드
- Ex06.java
package com.test.ajax;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex06.do")
public class Ex06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex06.java
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex06.jsp");
dispatcher.forward(req, resp);
}
}
- Ex06Data.java
package com.test.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex06data.do")
public class Ex06Data extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex06Data.java
// String txt1 = req.getParameter("txt1");
// System.out.println("txt1 : " + txt1);
//5초 동안 업무를 잠시 중단...
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
PrintWriter writer = resp.getWriter();
writer.write("ajax:" + String.format("%tT", now));
writer.close();
}
}
- ex06.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body class="narrow">
<!-- ex06.jsp -->
<h1>Ajax <small>jQuery</small></h1>
<div>
<input type="text" id="txt1">
<input type="button" value="확인" id="btn1">
<div id="div1"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$('#btn1').click(()=>{
//$(검색 태그).메소드()
//ajax 요청
//- ajax.send();
$.ajax({
//페이지 요청 정보
type: 'GET',
url: '/ajax/ex06data.do',
//데이터 전송(QueryString + GET/POST)
data: 'txt1=' + $('#txt1').val(),
//데이터 수신
success: function(result) {
$('#div1').text(result);
},
//ajax 예외 처리
error: function(a,b,c) {
console.log(a,b,c);
}
});
});
$('#btn1').click(()=>{
//Ajax, 비동기(async)
//네트워크 통신
//1. 동기 통신
//2. 비동기 통신
$.ajax({
type: 'GET',
url : '/ajax/ex06data.do',
async : true, //비동기(true), 동기(false)
success : function(result) {
$('#div1').text(result);
},
error : function(a,b,c) {
console.log(a,b,c);
}
});
});
</script>
</body>
</html>
■ 3. 다양한 방법 통신
- 필요 파일
- com.test.ajax > "Ex07.java"
- vies > "ex07.jsp"
- com.test.ajax > "Ex07Data.java"
■ 3. 소스코드
- Ex07.java
package com.test.ajax;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex07.do")
public class Ex07 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex07.java
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex07.jsp");
dispatcher.forward(req, resp);
}
}
- Ex07Data.java
- m1~m2 : Text 형식
- m3~m4 : XML 형식
- m5~m6 : JSON 형식
package com.test.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ex07data.do")
public class Ex07Data extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex07Data.java
String type = req.getParameter("type");
if (type.equals("1")) {
m1(req, resp);
} else if (type.equals("2")) {
m2(req, resp);
} else if (type.equals("3")) {
m3(req, resp);
} else if (type.equals("4")) {
m4(req, resp);
} else if (type.equals("5")) {
m5(req, resp);
} else if (type.equals("6")) {
m6(req, resp);
}
}
private void m6(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
List<AddressDTO> list = dao.listAddress();
/*
[
{
"seq" : "1",
"name" : "이름",
"age" : 20,
"tel" : "010"
"address" : "주소"
}
,
{
"seq" : "1",
"name" : "이름",
"age" : 20,
"tel" : "010"
"address" : "주소"
},
]
*/
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
String temp = "";
temp += ("[");
for (AddressDTO dto : list) {
temp += "{";
temp += String.format("\"seq\": \"%s\",", dto.getSeq());
temp += String.format("\"name\": \"%s\",", dto.getName());
temp += String.format("\"age\": %s,", dto.getAge());
temp += String.format("\"tel\": \"%s\",", dto.getTel());
temp += String.format("\"address\": \"%s\"", dto.getAddress());
temp += "}";
temp += ",";
}
temp = temp.substring(0, temp.length()-1);
temp += "]";
writer.print(temp);
writer.close();
}
private void m5(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
ResearchDTO dto = dao.getResearch(1);
/*
JSON
- 키와 값을 쌍옴표로 표기한다.
- 메소드는 표시 불가
{
"키" : "값",
"키" " "값"
}
[ 10, 20, 30 ]
[
{
"키" : "값"
"키" : "값"
}
]
{
"question" : "질문"
}
*/
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("{");
writer.printf("'question' : \"%s\"", dto.getQuestion());
writer.print("}");
writer.close();
}
private void m4(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
List<AddressDTO> list = dao.listAddress();
/*
<?xml version='1.0' encoding='UTF-8'?>
<list>
<item>
<seq>1</seq>
<name>홍길동</name>
<age>20</age>
<tel>010</tel>
<address>서울시</address>
</item>
</list>
*/
resp.setContentType("text/xml");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("<?xml version='1.0' encoding='UTF-8'?>");
writer.print("<list>");
for (AddressDTO dto : list) {
writer.print("<item>");
writer.printf("<seq>%s</seq>", dto.getSeq());
writer.printf("<name>%s</name>", dto.getName());
writer.printf("<age>%s</age>", dto.getAge());
writer.printf("<tel>%s</tel>", dto.getTel());
writer.printf("<address>%s</address>", dto.getAddress ());
writer.print("</item>");
}
writer.print("</list>");
writer.close();
}
private void m3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
ResearchDTO dto = dao.getResearch(1);
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.print("<?xml version='1.0' encoding='UTF-8'?>");
writer.printf("<question id='q1'>%s</question>"
, dto.getQuestion());
writer.close();
}
private void m2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
List<AddressDTO> list = dao.listAddress();
//CSV
String temp = "";
for (AddressDTO dto : list) {
temp += String.format("%s,%s,%s,%s,%s\r\n"
, dto.getSeq()
, dto.getName()
, dto.getAge()
, dto.getTel()
, dto.getAddress());
}
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print(temp);
writer.close();
}
private void m1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AjaxDAO dao = new AjaxDAO();
int count = dao.count();
//서버가 브라우저(Ajax)에게 건내는 데이터 이런 형식이다~ 알려주는 작업
resp.setContentType("text/plain"); //텍스트 형식
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print(count + "");
writer.close();
}
}
- ex07.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body class="narrow">
<!-- ex07.jsp -->
<h1>Ajax <small>응답 데이터 형식</small></h1>
<div>
<h2>Text</h2>
<input type="button" value="확인" id="btn1">
<div id="div1"></div>
<hr>
<h2>XML</h2>
<input type="button" value="확인" id="btn2">
<div id="div2"></div>
<hr>
<h2>JSON(***)</h2>
<input type="button" value="확인" id="btn3">
<div id="div3"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$('').click(()=>{
$.ajax({
type: 'GET',
url: '/ajax/ex07data.do',
data: 'type=1',
//서버가 Ajax에게 돌려주는 데이터 형식(text)
datatype: 'text',
success: (result)=>{
$('#div1').text(result);
},
error: (a,b,c)=>console.log(a,b,c)
});
});
$('#btn1').click(()=>{
$.ajax({
type: 'GET',
url: '/ajax/ex07data.do',
data: 'type=2',
datatype: 'text',
success: (result)=>{
const lines = result.split('\r\n');
lines.forEach(line=>{
const items = line.split(',');
$('#div1').append(
`
<div>\${items[1]} - \${items[4]}</div>
`
);
});
},
error: (a,b,c)=>console.log(a,b,c)
});
});
$('#btn2').click(()=>{
$.ajax({
type: 'GET',
url: '/ajax/ex07data.do',
data: 'type=4',
dataType: 'xml',
success: (result) => {
//$('#div2').text(result);
//$('#div2').text( $(result).find('question').text() );
//$('#div2').text( $(result).find('#q1').text() );
$(result).find('item').each((index, item)=>{
$('#div2').append(
`
<div>
\${$(item).find('seq').text()}
:
\${$(item).find('name').text()}
:
\${$(item).find('address').text()}
</div>
`
);
});
},
error: (a,b,c) => console.log(a,b,c)
});
});
$('#btn3').click(() => {
$.ajax({
type: 'GET',
url: '/ajax/ex07data.do',
data: { type: 6 },
dataType: 'json',
success: (result) => {
$(result).each((index, item) => {
$('#div3').append(
$('<div>').text(item.name)
);
});
},
error: (xhr, status, error) => {
console.log(xhr, status, error);
}
});
});
</script>
</body>
</html>
■ 실행 결과
728x90
'Server' 카테고리의 다른 글
AJAX STEP 5 - 주소록 조회 (0) | 2023.05.16 |
---|---|
AJAX STEP 4 - ID 중복 검사 (0) | 2023.05.16 |
AJAX STEP 2 - Push Server (0) | 2023.05.15 |
Servlet + JSP STEP 4 - Memo (0) | 2023.05.15 |
AJAX STEP 1 - 기초 (0) | 2023.05.12 |