AJAX
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
$는 객체 : $()뿐 아니라 $. 찍을 수 있다
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<button id="exam01">Exam01</button>
<script>
$("#exam01").on("click",function(){
$.ajax({
url:"exam01.ajax"
})
})
</script>
</body>
</html>
$.ajax(자바스크립트객체)
[] 배열
{} 객체
키값을 url로 쓰지 않으면 ajax 쓸 이유 없음
AJAX로 리퀘스트 보내기
클라이언트가 서버에 데이터를 보내는 방법
1. submit
2. url에 get방식을 흉내내기
-> 페이지가 전환되는 방식
AJAX : 페이지 전환없이 데이터를 서버와 주고 받는 기술
(Asynchronous JavaScript And XML)
: 비동기 매커니즘을 구현할 때 쓰이는 기술
(과거에는 XML 현재는 JSON)
비동기화 : 서로 응답을 기다리지 않고 자기 할일을 하다가 응답이 오면 그때 응답 처리
AJAX WITH PARAMETER
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<button id="exam01">Exam01</button>
<button id="exam02">Exam02</button>
<script>
$("#exam01").on("click",function(){
$.ajax({url:"exam01.ajax"})
})
$("#exam02").on("click",function(){
$.ajax({
url:"exam02.ajax",
type:"get",
data:{
name:"jack",
msg:"Hello AJAX"
}
})
})
</script>
</body>
</html>
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}
else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
네트워크 탭은 우리가 주고 받는 데이터가 어떤값인지 모니터링 한 기록을 볼 수 있다.
Query String Parameters 가 존재하면 일단 데이터가 보내진 것
( 자동화 프로그램 제작시 셀레니움과 네트워크 패킷 주고 받는 것을 연동해서 )
POST 방식으로 변경
체이닝 기법 (빌더 기법)
리턴된값 .done(function(){})
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<button id="exam01">Exam01</button>
<button id="exam02">Exam02</button>
<button id="exam03">Exam03</button>
<script>
$("#exam01").on("click",function(){
$.ajax({url:"exam01.ajax"})
})
$("#exam02").on("click",function(){
$.ajax({
url:"exam02.ajax",
type:"post",
data:{
name:"jack",
msg:"Hello AJAX"
}
})
})
$("#exam03").on("click",function(){
$.ajax({
url:"exam03.ajax"
}).done(function(resp){
console.log(resp);
})
})
</script>
</body>
</html>
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}else if(cmd.contentEquals("/exam03.ajax")){
response.getWriter().append("Hello AJAX Done");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
resp에 담는 값은 일단 String 그 후에 필요에 따라 변화해서 사용
프론트 컨트롤러와 JSP가
리퀘스트 리스폰스 공유
forward.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
forward forward forward
</body>
</html>
AJAXController.java
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}else if(cmd.contentEquals("/exam03.ajax")){
request.
getRequestDispatcher("forward.jsp").
forward(request, response);
// ajax에 대한 response는 뭘 해도 String 값이다
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
ajax에 대한 response는 뭘 해도 String 값이다
실패했을 경우 동작
예외 발생
.fail
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<button id="exam01">Exam01</button>
<button id="exam02">Exam02</button>
<button id="exam03">Exam03</button>
<button id="exam04">Exam04</button>
<script>
$("#exam01").on("click",function(){
$.ajax({url:"exam01.ajax"})
})
$("#exam02").on("click",function(){
$.ajax({
url:"exam02.ajax",
type:"post",
data:{
name:"jack",
msg:"Hello AJAX"
}
})
})
$("#exam03").on("click",function(){
$.ajax({
url:"exam03.ajax"
}).done(function(resp){
console.log(resp);
})
})
$("#exam04").on("click",function(){
$.ajax({
url:"exam04.ajax"
}).done(function(){
console.log("성공!");
}).fail(function(error1,error2){
console.log(error1);
console.log(error2);
})
})
</script>
</body>
</html>
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}else if(cmd.contentEquals("/exam03.ajax")){
// response.getWriter().append("Hello AJAX Done");
request.
getRequestDispatcher("forward.jsp").
forward(request, response);
// ajax에 대한 response는 뭘 해도 String 값이다
}else if(cmd.contentEquals("/exam04.ajax")){
Integer.parseInt("A");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
성공했을 때의 동작과 실패했을 때의 동작을 미리 정해 놓을 수 있음
복잡한 데이터를 받을 경우
스트링을 제이슨으로 변환해서 사용해야 함
package kh.backend.controller;
import java.io.IOException;
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("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}else if(cmd.contentEquals("/exam03.ajax")){
// response.getWriter().append("Hello AJAX Done");
request.
getRequestDispatcher("forward.jsp").
forward(request, response);
// ajax에 대한 response는 뭘 해도 String 값이다
}else if(cmd.contentEquals("/exam04.ajax")){
Integer.parseInt("A");
}else if(cmd.contentEquals("/exam05.ajax")){
response.getWriter().append("{name: 'Tom', msg:'Ajax Practice'}");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
$("#exam05").on("click",function(){
$.ajax({
url:"exam05.ajax"
}).done(function(resp){
console.log(resp);
console.log(resp.name);
console.log(resp.msg);
})
})
자바스크립트 객체에 . 찍으면 내부 값 출력 가능
객체 형태로 받아졌지만 내용을 꺼낼수 없는 이유
-> 객체가 아니라 스트링으로 받아짐
-> 스트링을 제이슨으로 변환해서 사용해야 함
JSON.parse
$("#exam05").on("click",function(){
$.ajax({
url:"exam05.ajax"
}).done(function(resp){
//JSON.parse : String to JSON
console.log(resp);
resp = JSON.parse(resp);
console.log(resp.name);
console.log(resp.msg);
})
})
GSON 라이브러리 사용
package kh.backend.controller;
import java.io.IOException;
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.JsonObject;
@WebServlet("*.ajax")
public class AJAXController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
System.out.println(cmd);
if(cmd.contentEquals("/exam01.ajax")) {
System.out.println("기본 AJAX");
}else if(cmd.contentEquals("/exam02.ajax")){
System.out.println("AJAX WITH PARAMETER");
String name = request.getParameter("name");
String msg = request.getParameter("msg");
System.out.println(name +" : "+ msg);
}else if(cmd.contentEquals("/exam03.ajax")){
// response.getWriter().append("Hello AJAX Done");
request.
getRequestDispatcher("forward.jsp").
forward(request, response);
// ajax에 대한 response는 뭘 해도 String 값이다
}else if(cmd.contentEquals("/exam04.ajax")){
Integer.parseInt("A");
}else if(cmd.contentEquals("/exam05.ajax")){
JsonObject respObj = new JsonObject();
respObj.addProperty("name", "tom");
respObj.addProperty("msg", "Ajax Practice");
response.getWriter().append(respObj.toString());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
respObj 를 2개 보낼 때
else if(cmd.contentEquals("/exam05.ajax")){
JsonObject respObj1 = new JsonObject();
respObj1.addProperty("name", "tom");
respObj1.addProperty("msg", "Ajax Practice");
JsonObject respObj2= new JsonObject();
respObj2.addProperty("name", "mike");
respObj2.addProperty("msg", "Fool tom");
response.getWriter().append(respObj1.toString());
response.getWriter().append(respObj2.toString());
}
-> append도 2번?
-> 중괄호 2번 나오는 JSON은 없음 -> 분석 불가
-> 올바른 방법 [{ },{ }] : JSON Array
else if(cmd.contentEquals("/exam05.ajax")){
JsonObject respObj1 = new JsonObject();
respObj1.addProperty("name", "tom");
respObj1.addProperty("msg", "Ajax Practice");
JsonObject respObj2= new JsonObject();
respObj2.addProperty("name", "mike");
respObj2.addProperty("msg", "Fool tom");
JsonArray respArr = new JsonArray();
respArr.add(respObj1);
respArr.add(respObj2);
response.getWriter().append(respArr.toString());
}
jsp 출력부분도 배열에 맞게 변경해야 함
for 문으로 배열 출력
$("#exam05").on("click",function(){
$.ajax({
url:"exam05.ajax"
}).done(function(resp){
//JSON.parse : String to JSON
console.log(resp);
resp = JSON.parse(resp);
for(var i = 0 ; i< resp.length; i++){
console.log(resp[i].name +" : "+resp[i].msg);
}
})
})
dataType:"json"
스트링으로 받아
resp = JSON.parse(resp);
하던가
바로 json으로 받을 수 있음
$("#exam05").on("click",function(){
$.ajax({
url:"exam05.ajax",
dataType:"json"
}).done(function(resp){
//JSON.parse : String to JSON
console.log(resp);
for(var i = 0 ; i< resp.length; i++){
console.log(resp[i].name +" : "+resp[i].msg);
}
//parse 대신
})
})
jsp를 응답에 담아서 보냈을 경우
일반적으로 페이지 상단에서 인코딩이 되지만
ajax로 응답을 보낼때에는 스트링형으로가서 한글이 깨짐
별도로 response 인코딩 해줘서 보내야함
response.setCharacterEncoding("utf8");
else if(cmd.contentEquals("/exam05.ajax")){
response.setCharacterEncoding("utf8");
JsonObject respObj1 = new JsonObject();
respObj1.addProperty("name", "tom");
respObj1.addProperty("msg", "Ajax Practice");
JsonObject respObj2= new JsonObject();
respObj2.addProperty("name", "mike");
respObj2.addProperty("msg", "Fool tom");
JsonArray respArr = new JsonArray();
respArr.add(respObj1);
respArr.add(respObj2);
response.getWriter().append(respArr.toString());
}
'디지털 컨버전스 > AJAX' 카테고리의 다른 글
[문제] UTF-8에서 ajax를 사용 시 한글깨짐 현상(??)이 발생 (0) | 2020.05.15 |
---|---|
[AJAX] 파파고 연동 (0) | 2020.05.11 |
[AJAX] HTTP 상태 코드 / Array list 데이터 가져오기 / 무한스크롤 (0) | 2020.05.11 |
[AJAX] 아이디 중복체크 (0) | 2020.05.11 |