728x90
★ 데이터 송수신
■ 필요 파일들
- com.test.ajax > "Ex10.java"
- views > "ex10.jsp"
- com.test.ajax > "Ex10Data.java"
■ 소스코드
- Ex10.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("/ex10.do")
public class Ex10 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex10.java
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex10.jsp");
dispatcher.forward(req, resp);
}
}
- Ajax 템플릿
- 1. Object > 주력
- 2. QueryString > serialize()
// 템플릿
$('#form1').submit(()=> {
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: '',
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
- Ex10Data.java
package com.test.ajax;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
@WebServlet("/ex10data.do")
public class Ex10Data extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex10Data.java
// m1(req, resp);
// m2(req, resp);
// m3(req, resp);
// m4(req, resp);
m5(req, resp);
}
private void m5(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//List<DTO>
AjaxDAO dao = new AjaxDAO();
List<AddressDTO> list = dao.listAddress();
JSONArray arr = new JSONArray();
for (AddressDTO dto : list) {
JSONObject obj = new JSONObject();
obj.put("name", dto.getName());
obj.put("age", dto.getAge());
obj.put("address", dto.getAddress());
arr.add(obj);
}
System.out.println(arr);
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.print(arr);
writer.close();
}
private void m4(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//DTO
AjaxDAO dao = new AjaxDAO();
ResearchDTO dto = dao.getResearch(1);
JSONObject obj = new JSONObject();
//obj.put("name", "홍길동");
//obj.put("age", "20");
obj.put("question", dto.getQuestion());
obj.put("seq", dto.getSeq());
//{"name":"홍길동","age":"20"}
//System.out.println(obj.toString());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.print(obj);
writer.close();
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Ex10Data.java
// m1(req, resp);
// m2(req, resp);
m3(req, resp);
}
private void m3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("txt1"));
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line = reader.readLine();
reader.close();
// org.json
// JSON 포맷의 문자열 > 자바 오브젝트로 변환
JSONParser parser = new JSONParser();
try {
//JSON Object > 자바 오브젝트
JSONObject obj = (JSONObject)parser.parse(line);
System.out.println(obj.get("txt1"));
System.out.println(obj.get("txt2"));
System.out.println(obj.get("txt3"));
System.out.println(obj.get("txt4"));
System.out.println(obj.get("txt5"));
} catch (ParseException e) {
e.printStackTrace();
}
}
private void m2(HttpServletRequest req, HttpServletResponse resp) {
//String list = req.getParameter("list");
//System.out.println(list);
String[] list = req.getParameterValues("list");
for (String item : list) {
System.out.println(item);
}
}
private void m1(HttpServletRequest req, HttpServletResponse resp) {
//String data = req.getParameter("data");
//System.out.println(data);
String txt1 = req.getParameter("txt1");
String txt2 = req.getParameter("txt2");
String txt3 = req.getParameter("txt3");
String txt4 = req.getParameter("txt4");
String txt5 = req.getParameter("txt5");
System.out.println(txt1);
System.out.println(txt2);
System.out.println(txt3);
System.out.println(txt4);
System.out.println(txt5);
}
}
- ex10.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>
<h1>Ajax</h1>
<form id="form1">
<div>
<input type="text" name="txt1" id="txt1" value="강아지">
</div>
<div>
<input type="text" name="txt2" id="txt2" value="고양이">
</div>
<div>
<input type="text" name="txt3" id="txt3" value="토끼">
</div>
<div>
<input type="text" name="txt4" id="txt4" value="사자">
</div>
<div>
<input type="text" name="txt5" id="txt5" value="호랑이">
</div>
<div>
<input type="submit" value="보내기" id="btn1">
</div>
</form>
<hr>
<div>
<input type="button" value="가져오기" id="btn2">
</div>
<div id="result" class="panel" title="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
// 템플릿
/*
$('#form1').submit(()=> {
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: '',
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//***방법 1***
/*
$('#form1').submit(()=> {
let data = 'txt1=' + $('#txt1').val()
+ '&txt2=' + $('#txt2').val()
+ '&txt3=' + $('#txt3').val()
+ '&txt4=' + $('#txt4').val()
+ '&txt5=' + $('#txt5').val();
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: data,
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//***방법 2***
/*
$('#form1').submit(()=> {
//객체 전송
const obj = {
txt1: $('#txt1').val(),
txt2: $('#txt2').val(),
txt3: $('#txt3').val(),
txt4: $('#txt4').val(),
txt5: $('#txt5').val()
};
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: obj,
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//***방법3***
/*
$('#form1').submit(()=> {
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: {
txt1: '딸기',
txt2: '바나나',
txt3: '포도'
},
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//방법 4
/*
$('#form1').submit(()=> {
// alert($('#form1').serialize());
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
data: '$('#form1').serialize()',
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//1. Object > 주력
//2. QueryString > serialize()
//방법 5
/*
$('#form1').submit(()=> {
//String[] name = req.getParameterValues("name")
const list = [ '사과', '바나나', '딸기', '포도', '귤'];
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
traditional: true,
data: {
list: list
},
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
*/
//방법 6
$('#form1').submit(()=> {
const obj = {
txt1: $('#txt1').val(),
txt2: $('#txt2').val(),
txt3: $('#txt3').val(),
txt4: $('#txt4').val(),
txt5: $('#txt5').val()
};
//{"txt1":"강아지","txt2":"고양이","txt3":"토끼","txt4":"사자","txt5":"호랑이"}
//alert(JSON.stringify(obj));
$.ajax({
type: 'POST',
url: '/ajax/ex10data.do',
contentType: 'application/json', //줄때
data: JSON.stringify(obj),
//dataType: 'json', //받을때
success: (result)=>{},
error: (a,b,c)=>console.log(a,b,c)
});
event.preventDefault();
return false;
});
$('#btn2').click(()=> {
$.ajax({
type: 'GET',
url: '/ajax/ex10data.do',
dataType: 'json',
success: (result)=>{
// $('#result').append('<div>' + result.seq + '</div>');
// $('#result').append('<div>' + result.question + '</div>');
$(result).each((index, item) => {
$('#result').append('<div>' + item.name + '</div>');
$('#result').append('<div>' + item.age + '</div>');
$('#result').append('<div>' + item.address + '</div>');
$('#result').append('<hr>');
});
},
error: (a,b,c)=>console.log(a,b,c)
});
});
</script>
</body>
</html>
■ 실행 결과
728x90
'Server' 카테고리의 다른 글
AJAX STEP 8 - 일기장 AJAX (0) | 2023.05.17 |
---|---|
AJAX STEP 7 - 테이블 저장 AJAX (0) | 2023.05.17 |
AJAX STEP 5 - 주소록 조회 (0) | 2023.05.16 |
AJAX STEP 4 - ID 중복 검사 (0) | 2023.05.16 |
AJAX STEP 3 - Real AJAX 구현 (1) | 2023.05.16 |