Language/Java
[JAVA] $.ajax - jsonTest 코드
생각하는 감쟈🥔
2024. 6. 4. 12:35
js파일 추가 후 jquery 파일2개 넣기
lib에 Gson jar 파일 추가
JsonTest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript"
src ="<%=request.getContextPath()%>/js/jquery-3.7.1.js"></script>
<script type="text/javascript">
$(function() {
// 코드 내용
</script>
</head>
<body>
<form>
<input type="button" id="strBtn" value="문자열">
<input type="button" id="arrBtn" value="배 열">
<input type="button" id="objBtn" value="객체 ">
<input type="button" id="listBtn" value="리스트 ">
<input type="button" id="mapBtn" value="Map객체 ">
</form>
<h3> 응답 결과 출력</h3>
<div id="result"></div>
</body>
</html>
문자열 처리
// 문자열 처리
$("#strBtn").on('click',function(){
$.ajax({
// 요청 할때 필요한
url : "<%=request.getContextPath()%>/json/jsonTest.do",
type : "POST",
data : "choice=String",
// 응답 받았을 때
success : function(data) {
//data ="안니옹..."
let htmlCode = "<h3>문자열 응답 데이터</h3>";
htmlCode += data;
$("#result").html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : " + xhr.status);
}
}); // ajax
});
배열 처리
// 배열 처리
$("#arrBtn").on("click", function(){
$.ajax({
url : "<%= request.getContextPath()%>/json/jsonTest.do",
data : "choice=Array",
type : "GET",
success : function(data){
// data = [100,200,300,400,500];
let htmlCode = "<h3> 배열 응답 데이터 </h3>";
$.each(data, function(i,v){
htmlCode += i + "번째 자료 : " + v + "<br>";
})
$("#result").html(htmlCode);
},
error : function(xhr){
alert("오류 : " + xhr.status);
},
dataType : "json"
});
});
객체 처리
// 객체 처리
$("#objBtn").on("click", function(){
$.ajax({
url : "<%= request.getContextPath()%>/json/jsonTest.do",
data : "choice=Object",
type : "GET",
success : function(data){
// data = {"num":1,"name":"박수빈","age":24}
let htmlCode = "<h3> 객체 응답 데이터 </h3>";
htmlCode += "번호 : " + data.num + "<br>";
htmlCode += "이름 : " + data.name + "<br>";
htmlCode += "나이 : " + data.age + "<br>";
$("#result").html(htmlCode);
},
error : function(xhr){
alert("오류 : " + xhr.status);
},
dataType : "json"
});
});
리스트 처리
// 리스트 처리
$("#listBtn").on("click", function(){
$.ajax({
url : "<%= request.getContextPath()%>/json/jsonTest.do",
data : "choice=List",
type : "POST",
success : function(data){
/*
List >> [{"num":100,"name":"박수빈","age":20},
{"num":200,"name":"심재영","age":30},
{"num":300,"name":"김효진","age":40},
{"num":400,"name":"이창윤","age":50}];
*/
let htmlCode = "<h3> list 응답 데이터 </h3>";
$.each(data, function(i,v){
htmlCode += i + "번째 자료<br>";
htmlCode += "번호 : " + v.num +"<br>";
htmlCode += "이름 : " + v.name +"<br>";
htmlCode += "나이 : " + v.age +"<hr>";
})
$("#result").html(htmlCode);
},
error : function(xhr){
alert("오류 : " + xhr.status);
},
dataType : "json"
});
});
Map처리
// Map 처리
$("#mapBtn").on("click", function(){
$.ajax({
url : "<%= request.getContextPath()%>/json/jsonTest.do",
data : "choice=Map",
type : "POST",
success : function(data){
// Map >> {"name":"박수빈","tel":"010-2222-3333",
// "addr":"대전시 중구 용두동"}
let htmlCode = "<h3> Map 응답 데이터 </h3>";
// htmlCode +="name : " + data.name + "<br>";
// htmlCode +="tel : " + data.tel + "<br>";
// htmlCode +="addr : " + data.addr + "<br>";
$.each(data, function(i,v){
htmlCode += i + " : " + v + "<br>";
});
$("#result").html(htmlCode);
},
error : function(xhr){
alert("오류 : " + xhr.status);
},
dataType : "json"
});
});
TestVO
package kr.or.ddit.vo;
public class TestVO {
private int num;
private String name;
private int age;
public TestVO() { };
public TestVO(int num, String name, int age) {
super();
this.num = num;
this.name = name;
this.age = age;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
데이터 입력 Servlet (JsonTest.java)
package kr.or.ddit.json;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
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 com.google.gson.Gson;
import kr.or.ddit.vo.TestVO;
@WebServlet("/json/jsonTest.do")
public class JsonTest extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
// 파라미터 자료 받기
String choice = request.getParameter("choice");
Gson gson = new Gson();
String jsonData = null;
switch(choice) {
case "String" :
String str = "안니옹...";
jsonData = gson.toJson(str);
break;
case "Array" :
int[] arr = {100, 200, 300, 400, 500};
jsonData = gson.toJson(arr);
break;
case "Object" :
TestVO testVo = new TestVO(1,"박수빈",24);
jsonData = gson.toJson(testVo);
break;
case "List" :
ArrayList<TestVO> list = new ArrayList<TestVO>();
list.add(new TestVO(100, "박수빈", 20));
list.add(new TestVO(200, "심재영", 30));
list.add(new TestVO(300, "김효진", 32));
list.add(new TestVO(400, "이창윤", 31));
jsonData = gson.toJson(list);
break;
case "Map" :
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "박수빈");
map.put("tel", "010-2222-3333");
map.put("addr", "대전시 중구 용두동");
jsonData = gson.toJson(map);
break;
}
System.out.println(choice + " >> " + jsonData);
PrintWriter out = response.getWriter();
out.write(jsonData);
response.flushBuffer();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}