json의 ContentType
application/json
response 인코딩 설정시
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
ajax
$.ajax({
url : "경로",
type : "타입",
data : "전달할 데이터타입",
dataType : "응답받을 자료 종류 (json, html)"
success : function(data){
// 성공되었을 때 실행될 함수
},
error : function(xhr){
alert("오류코드 : " + xhr.status);
}
});
문자열/배열/객체/List/Map 처리
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JsonTest</title>
<script src="<%=request.getContextPath() %>/js/jquery-3.7.1.js"></script>
<script>
$(function(){
// 문자열 처리------------------------------------------------------------
$('#strBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=String",
success : function(data){
// data = "꽥꽥"
let htmlCode = "<h3>문자열 응답데이터</h3><hr>"
htmlCode += data;
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
// 배열 처리------------------------------------------------------------
$('#arrBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=Array",
success : function(data){
// data = [100,200,300,400,500] > 배열로 저장
let htmlCode = "<h3>배열 응답데이터</h3><hr>"
$.each(data, function(i, v){
htmlCode += i + "번째 자료 : " + v + "<br>"; // this = v 와 동일
})
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
// 객체 처리------------------------------------------------------------
$('#objBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=Object",
success : function(data){
// data = {"num":1,"name":"아잠만","age":5}
let htmlCode = "<h3>객체 응답데이터</h3><hr>"
htmlCode += "번호 : "+data.num+"<br>";
htmlCode += "이름 : "+data.name+"<br>";
htmlCode += "나이 : "+data.age+"<br>";
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
// 리스트 처리------------------------------------------------------------
$('#listBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=List",
success : function(data){
/* data = > 배열처럼 출력
[{"num":100,"name":"배고파","age":20},
{"num":200,"name":"뽀야미","age":15},
{"num":300,"name":"아잠만","age":5},
{"num":400,"name":"리처드","age":5}] */
let htmlCode = "<h3>리스트 응답데이터</h3><hr>"
$.each(data, function(i, v){
htmlCode += i+"번째 자료 <br>"+
"번호 : "+v.num+"<br>"+
"이름 : "+v.name+"<br>"+
"나이 : "+v.age+"<br><hr>"; // this = v 와 동일
})
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
// map 처리------------------------------------------------------------
$('#mapBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=Map",
success : function(data){
// data = {"name":"뽀야미","tel":"010-0000-0000","addr":"동물의숲"} > 객체 모양
let htmlCode = "<h3>Map객체 응답데이터</h3><hr>"
htmlCode += "이름 : "+ data.name+"<br>";
htmlCode += "전화번호 : "+data.tel+"<br>";
htmlCode += "주소 : "+data.addr+"<br>";
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
});
</script>
</head>
<body>
<form action="">
<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>
<div id="result"></div>
</body>
</html>
Servlet
package kr.or.ddit.json;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
// 객체(VO) 처리------------------------------------------------------------
case "Object":
TestVO tVo = new TestVO(1, "아잠만", 5);
jsonData = gson.toJson(tVo); // 직렬화 하지 않았으므로 그냥 보냄
// jsonData = gson.toJson(tVo, TestVO.class); > 직렬화한 데이터를 역직렬화하는법
break;
// List 처리------------------------------------------------------------
case "List":
List<TestVO> list = new ArrayList<TestVO>();
list.add(new TestVO(100, "배고파", 20));
list.add(new TestVO(200, "뽀야미", 15));
list.add(new TestVO(300, "아잠만", 5));
list.add(new TestVO(400, "리처드", 5));
jsonData = gson.toJson(list);
break;
// Map 처리------------------------------------------------------------
case "Map":
Map<String, String> map = new HashMap<String, String>();
map.put("name", "뽀야미");
map.put("tel", "010-0000-0000");
map.put("addr", "동물의숲");
jsonData = gson.toJson(map);
break;
default:
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 {
// TODO Auto-generated method stub
doGet(request, response);
}
}
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;
}
}
each문
+each문은 객체타입을 반복문으로 뽑아낼수도 있다
// map 처리------------------------------------------------------------
$('#mapBtn').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/json/jsonTest.do", // action 주소
type : "POST",
data : "choice=Map",
success : function(data){
// data = {"name":"뽀야미","tel":"010-0000-0000","addr":"동물의숲"}
let htmlCode = "<h3>Map객체 응답데이터</h3><hr>"
/*
htmlCode += "이름 : "+ data.name+"<br>";
htmlCode += "전화번호 : "+data.tel+"<br>";
htmlCode += "주소 : "+data.addr+"<br>";
*/
$.each(data, function(i,v){
htmlCode+= i+ ": "+ v+"<br>";
})
$('#result').html(htmlCode);
},
dataType : "json", // 응답으로 받을 자료의 종류를 지정한다.
error : function(xhr){
alert("오류 코드 : "+xhr.status);
}
})
});
i는 key값, v는 value값
문제 - Lprod출력(ajax)
기본 설정
더보기
LprodVO
package kr.or.ddit.vo;
public class LprodVO {
private int lprod_id;
private String lprod_gu;
private String lprod_nm;
public LprodVO() {
}
public int getLprod_id() {
return lprod_id;
}
public void setLprod_id(int lprod_id) {
this.lprod_id = lprod_id;
}
public String getLprod_gu() {
return lprod_gu;
}
public void setLprod_gu(String lprod_gu) {
this.lprod_gu = lprod_gu;
}
public String getLprod_nm() {
return lprod_nm;
}
public void setLprod_nm(String lprod_nm) {
this.lprod_nm = lprod_nm;
}
@Override
public String toString() {
return "LprodVO [lprod_id=" + lprod_id + ", lprod_gu=" + lprod_gu + ", lprod_nm=" + lprod_nm + "]";
}
}
Mapper
<?xml version="1.0" encoding="UTF-8"?>
<!-- 이 문서는 myBatis에서 처리할 SQL문을 작성하는 문서입니다 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lprod">
<select id="list" resultType="lVo">
select * from lprod
</select>
</mapper>
mybatis-config (추가한 부분)
<configuration>
<typeAliases>
<typeAlias type="kr.or.ddit.vo.LprodVO" alias="lVo"/>
</typeAliases>
<!-- DB에서 사용되는 SQL문이 작성된 mapper파일을 등록하는 부분 -->
<mappers>
<mapper resource="kr/or/ddit/mybatis/mappers/lprod-mapper.xml"/>
</mappers>
</configuration>
Dao
package kr.or.ddit.json.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.LprodVO;
public class LprodDao implements ILprodDao {
private static LprodDao dao;
private LprodDao() {
}
public static LprodDao getInstance() {
if(dao==null) {
dao = new LprodDao();
}
return dao;
}
@Override
public List<LprodVO> allList() {
SqlSession session = null;
List<LprodVO> list = null;
try {
session = MyBatisUtil.getSqlSession();
list = session.selectList("lprod.list");
} catch (Exception e) {
// TODO: handle exception
} finally {
if(session!=null) try {
session.close();
} catch (Exception e2) {
}
}
return list;
}
}
Service
package kr.or.ddit.json.service;
import java.util.List;
import kr.or.ddit.json.dao.LprodDao;
import kr.or.ddit.vo.LprodVO;
public class LprodService implements ILprodService{
private static LprodService service;
private LprodDao dao;
private LprodService() {
dao=LprodDao.getInstance();
}
public static LprodService getInstance() {
if(service==null) service = new LprodService();
return service;
}
@Override
public List<LprodVO> allList() {
// TODO Auto-generated method stub
return dao.allList();
}
}
Servlet
package kr.or.ddit.json.controller;
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;
import com.google.gson.Gson;
import kr.or.ddit.json.service.LprodService;
import kr.or.ddit.vo.LprodVO;
@WebServlet("/lprodList.do")
public class LprodList extends HttpServlet {
private static final long serialVersionUID = 1L;
private LprodService service = LprodService.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
List<LprodVO> list = service.allList();
Gson gson = new Gson();
String json = gson.toJson(list);
PrintWriter out = response.getWriter();
out.write(json);
response.flushBuffer();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
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 src="<%=request.getContextPath()%>/js/jquery-3.7.1.js"></script>
<script>
$(function(){
$('#lprodList').on('click',function(){
$.ajax({
url : "<%=request.getContextPath()%>/lprodList.do",
type : "GET",
success : function(data){
let htmlCode = "<table border='1'><tr><th>LPROD_ID</th><th>LPROD_GU</th><th>LPROD_NM</th></tr>";
$.each(data, function(i,v){
htmlCode += "<tr><td>"+v.lprod_id+"</td>";
htmlCode += "<td>"+v.lprod_gu+"</td>";
htmlCode += "<td>"+v.lprod_nm+"</td></tr>";
})
htmlCode+="</table>"
$('#result').html(htmlCode);
},
error : function(xhr){
alert("오류 코드 : "+xhr.status)
},
dataType : "json"
});
})
})
</script>
</head>
<body>
<input type="button" id="lprodList" value="Lprod자료 가져오기">
<br><br>
<div id="result"></div>
</body>
</html>
문제2 - 동기방식 처리
비동기와 동기의 차이
1. 주소가 변경되는 지의 여부
2. 서버에서 처리중일 때 클라이언트가 다른 작업을 할 수 있느냐의 차이
jsp
해당 페이지로 이동하는 방법
location.href = "경로"
<%@ 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 src="<%=request.getContextPath()%>/js/jquery-3.7.1.js"></script>
<script>
$(function(){
$('#lprodList2').on('click',function(){
location.href = "<%=request.getContextPath()%>/lprodList2.do";
})
})
</script>
</head>
<body>
<input type="button" id="lprodList2" value="Lprod자료 가져오기(Non Ajax)">
<br>
<br>
<div id="result"></div>
</body>
</html>
servlet
package kr.or.ddit.json.controller;
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;
import com.google.gson.Gson;
import kr.or.ddit.json.service.LprodService;
import kr.or.ddit.vo.LprodVO;
@WebServlet("/lprodList2.do")
public class LprodList2 extends HttpServlet {
private static final long serialVersionUID = 1L;
private LprodService service = LprodService.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
List<LprodVO> list = service.allList();
request.setAttribute("list", list);
request.getRequestDispatcher("/jsonTest/lprodtable.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
테이블을 출력하는 jsp
<%@page import="kr.or.ddit.vo.LprodVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
List<LprodVO> list = (List<LprodVO>)request.getAttribute("list");
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border='1'><tr><th>LPROD_ID</th><th>LPROD_GU</th><th>LPROD_NM</th></tr>
<%
for(LprodVO vo : list){
int id = vo.getLprod_id();
String gu = vo.getLprod_gu();
String nm = vo.getLprod_nm();
%>
<tr><td><%=id %></td>
<td><%=gu %></td>
<td><%=nm %></td></tr>
<%
}
%>
</table>
</body>
</html>
'JAVA > HIGH JAVA' 카테고리의 다른 글
6/7 Homework (1) | 2024.06.07 |
---|---|
[JAVA] 파일 저장/다운 (0) | 2024.06.05 |
6/3 Homework - DB로 로그인, log4j 사용 (0) | 2024.06.03 |
[JAVA] 세션(HttpSession) (1) | 2024.06.03 |
5/31 Homework - 로그인(쿠키로 id기억) (0) | 2024.05.31 |