Jam's story
[JSP] AJAX 본문
1. AJAX(Asynchronous Javascript And XML) (프로그램 언어가 아니라 기술)
비동기적인 자바스크립트 + XML 데이터
JSON
ㄱ. 자바스크립트 언어를 사용해서 XML 데이터를 비동기적으로 서버-클라이언트 (간에 주고받는) 기술
xml 데이터를 자바스크립트 언어를 사용해 비동기적으로 처리하는 기술
ㄴ. 에이잭스 -- 에이작스 -- 아작스
ㄷ. 비동기적 의미 ? 웹 페이지를 다시 로드하지 않고 웹 페이지 업데이트
마치 스레드 처럼 서버 처리하는 동안 기다리지 않고, 또 다른 비동기 처리 요청 가능.
네이버 메인의 실시간으로 바뀌는 부분 ( 날씨 정보, 검색 , 뉴스 순위 )
기상청서버 네서버 연합뉴스서버
2. AJAX 장점
ㄱ. 페이지 전체 요청x -> 성능 향상
-수신하는 데이터의 양을 줄일 수 있다.
ㄴ. 마치 스레드처럼 서버 처리하는 동안 기다리지 않고 또다른 비동기 처리를 요청할 수 있다.
ㄷ. 서버 측 처리를 각각 PC에서 분산 처리 가능
3. AJAX 단점
ㄱ. 보안 취약 (오픈 소스)
ㄴ. 차별화 없음
ㄷ. 브라우저 호환성 체크
4. AJAX 활용
ㄱ. 회원가입
-우편번호 검색 / ID 중복체크
ㄴ. 한 줄 댓글 처리
등등
5. AJAX 처리를 위한 절차(방법)
ㄱ. 비동기적으로 처리하는 객체가 필요 - 브라우저마다 내장되어져 있음(XMLHttpRequest 객체)
-XMLHttpRequest 객체를 통해 웹 서버에 요청 -> js 또는 jquery + DOM 데이터를 표시(사용)
-모든 최신 브라우저(크롬, 엣지, 사파리, 익7 등)에서 XMLHttpRequest 제공
var 변수명 = new XMLHttpRequest()
- IES/6
var 변수명 = new ActiveObject("Microsoft. XMLHTTP");
var xmlHttp;
if(window. XMLHttpRequest){ //브라우저 버전따라 나눌 수 있다.
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp =
ㄴ. 요청에 대한 설정 + 요청(get,post)(일) 시킨다.
open()
send()
ㄷ. callback 콜백함수를 호출 (갔다오면 호출되는 함수)
요청 상태 체크 (잘갔다왔는지 결과물 가져왔는지) -> 결과값을 -> DOM 출력(처리)
6-1. GET방식 Ajax
ㄱ. XMLHttpRequest 객체
ㄴ. XMLHttpRequest 객체. open("GET", "/test. jsp?id=admin", true(true=비동기적))
-요청 설정 (실제 갔다오는게 아니라 일 시킨 것)
ㄷ. XMLHttpRequest 객체. send(null); -실제 요청
6-2. POST방식 Ajax
ㄱ. XMLHttpRequest 객체
파라미터가 붙지 않는다.
ㄴ. XMLHttpRequest 객체. open("POST", "/test. jsp") -요청 설정
ㄷ. XMLHttpRequest 객체. send("id=admin"); -실제 요청
POST: 보안적인 측면 필요할때 / 파일 업로드 할때 등
7. 최신 브라우저는 도메인 간의 엑세스는 허용하지 않는다. (네이버에서 다른 사이트 (kenik. com))
(보안상의 이유)
8. 최신 브라우저는 XMLHttpRequest 객체 대신 Fetch API를 사용할 수 있다.
9. XMLHttpRequest 객체의 메소드
ㄱ. new XMLHttpRequest()
ㄴ. abort() 현재 요청 취소
ㄷ. getAllResponseHeaders() 모든 응답 헤더 정보 얻어오는 메소드
ㄹ. getResponseHeader() 하나의 응답 헤더 정보만 얻어오는 메소드
**ㅁ. open(method, url, async, user, psw)
**ㅂ. send() --get
send(param string) --post
ㅅ. setRequestHeader()
10. XMLHttpRequest 객체의 속성
ㄱ. onreadystatechange - XMLHttpRequest 객체의 준비상태(readystate)가 바뀔때마다 호출되는 이벤트 함수 정의
onclick = function(){}처럼 클릭할때마다 호출되듯이 상태 바뀔때마다 호출
ㄴ. readyState :
0 요청이 초기화되지 않았다.
1 서버 연결 설정
2 요청 접수
3 요청 처리
4 요청이 완료되고 응답 준비가 되었다.
ㄷ. status 속성 : 요청 결과를 정수 반환
404 페이지를 찾을 수 없다
500
403 금지(다른 요청을 하게되면 금지)
[200 확인(오류없이 응답 잘 받아왔을 때)]
ㄹ. responseText : 응답 결과를 문자열(String) 반환(로 받았다)
ㅁ. responseXML : 응답 결과를 XML 반환(로 받았다)
ex02.jsp
<%@page import="java.util.Date"%>
<%@ page 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>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
$(document).ready(function (){
$("#btnAjax").on("click", function(event) {
$('#demo').load("ajax_info.txt", function (response, status, xhr) {
if(status == "success"){
alert("요청 성공");
}else if(status =="error"){
alert( xhr.status + ": " + xhr.statusText );
};
})
//$('#demo').load("ajax_info.txt"); 얘만 있으면 콜백함수까지 한 것, jquery쓰면 아주 간단 (대신 의미는 정확히 알기)
});//click
});//ready
</script>
</head>
<body>
서버요청시간: <%=new Date().toLocaleString() %>
<input type="button" value="js ajax" onclick="load('ex02_ajax_info.txt')"/><br>
<input type="button" value="jquery ajax" id="btnAjax" /><br>
<div id="demo"></div>
<script>
var httpRequest;
function getXMLHttpRequest(){ //브라우저 종류, 버전마다 해당하는 비동기 처리 요청 객체 얻어오는 함수
if( window.ActiveXObject ){ // IE window.ActiveXObject가 있다면 (윈도우 5,6점대로 옛날버전)
try{
return new ActiveXObject("Msxml2.XMLHTTP"); // 이게 적용되면 이거 가져오고
}catch(e){
try{
return new ActiveXObject("Microsoft.XMLHTTP"); //안되면 이거 가져오고
}catch(e){
return null;
}
}
}else if( window.XMLHttpRequest ){ //window.XMLHttpRequest가 있다면
return new XMLHttpRequest(); //우리라면 다 필요없고 이거만 있어도 됨 (구버전 아니니까)
}else{
return null;
}
}
function load(url){
//alert("test")
//1. XMLHttpRequest 객체 얻어오기 : new XMLHttpRequest
httpRequest = getXMLHttpRequest();
//2. 요청 설정 : open()
httpRequest.onreadystatechange = callback; //콜백함수 호출
httpRequest.open("GET", url, true); //100프로 true(비동기적)이고 false줄일 없다
//3. 요청 실행 : send()
httpRequest.send(); //null줘도 좋고 안줘도 좋고
}
function callback() {
if (httpRequest.readyState == 4) {
if (httpRequest.status==200) { //요청잘했고 결과물도 잘 받아왔다면
alert(httpRequest.responseText);
$("#demo").html(httpRequest.responseText);
} else {
alert(">Ajax 요청 실패"+httpRequest.status);
}
}
}
</script>
</body>
</html>
ex02_02.jsp
<%@page import="java.util.Date"%>
<%@ page 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>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
$(document).ready(function (){
$("input").on("click", function(event) {
$('#demo').load("ex02_ajax_info.txt", function (responseText,textStatus,jqXHR) {
if(textStatus == "success"){
/* $(this).append(responseText);
alert("요청 성공"); */
var names=responseText.split(",");
for(let name of names){
$("#demo").append($("<li></li>").text(name));
}
}else if(textStatus =="error"){
/* alert( xhr.status + ": " + xhr.statusText );
*/
};
})
//$('#demo').load("ajax_info.txt"); 얘만 있으면 콜백함수까지 한 것, jquery쓰면 아주 간단 (대신 의미는 정확히 알기)
});//click
});//ready
</script>
</head>
<body>
서버요청시간: <%=new Date().toLocaleString() %>
<input type="button" value="jquery ajax" id="btnAjax" /><br>
<div id="demo"></div>
<script>
</script>
</body>
</html>
ex03.jsp
<%@ page 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>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
</head>
<body>
<ol id="new-projects"></ol>
<script>
$(function() {
$("#new-projects").load("ex03_load.html #projects li");
});
</script>
</body>
</html>
ex03_load.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<ul id="projects">
<li>jQuery</li>
<li>jQuery UI</li>
<li>jQuery Mobile</li>
<li>QUnit</li>
<li>Sizzle</li>
</ul>
</body>
</html>
sql
with temp as (
select empno, ename, sal,
rank() over(order by sal desc) r
from emp
)
select * from temp
where r <= 5 ;
update emp
set sal=500
where empno=7839;
commit;
update emp
set sal=4000
where empno=7839;
commit;
update emp
set sal=5000
where empno=7839;
commit;
ex04.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="java.util.Calendar"%>
<%@page import="com.util.ConnectionProvider"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// TOP 5
String sql = "with temp as ("
+" select empno, ename, sal, "
+" rank() over(order by sal desc) r "
+" from emp "
+")"
+" select * from temp "
+" where r <= 5 ";
Calendar cal = Calendar.getInstance();
String now = String.format("%tT", cal);
String responseText = "<h3>" + now + "</h3>";
try{
conn = ConnectionProvider.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
int rank = rs.getInt("r");
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
double sal = rs.getDouble("sal");
responseText +=String.format("<li>[%d] %d %s\t\t(%.2f)</li>"
, rank, empno, ename, sal);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
pstmt.close();rs.close();conn.close();
}catch(Exception e){}
}
%>
<%= responseText %>
1)sendRequest(url,params,method,callback)함수 ->ajax요청-> 응답
2)xhr=getXMLHttRequest();
3)onreadyStateChange속성 =callback;
get방식과 post방식으로 나눠짐
/**
* httpReqeust.js
*/
var httpRequest = null;
function getXMLHttpRequest(){
if(window.ActiveXObject){
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActivXObject("Microsoft.XMLHTTP");
} catch (e) {
return null;
}
}
}else if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else {
return null;
}
}
// 요청할 url, 파라미터, 콜백함수등록, get/post
function sendRequest(url,params,callback,method){
// xhr
httpRequest = getXMLHttpRequest();
var httpMethod= method?method:'GET';
if(httpMethod!='GET' && httpMethod!='POST') httpMethod='GET';
//id=adi&age=20 없으면 nulll
var httpParams = (params==null||params=="")?null:params;
var httpUrl = url;
if(httpMethod=='GET' && httpParams != null){
httpUrl= httpUrl +"?"+httpParams;
}
httpRequest.open(httpMethod,httpUrl,true); // true 비동기적..
// [XMLHTTP를 사용해서 통신할 때 규약]
// httpRequest.setRequestHeader('Content-Type','application/x-www-form-unlencoded');
httpRequest.onreadystatechange = callback;
httpParams = (httpMethod=='POST'?httpParams:null );
httpRequest.send( httpParams); // 요청처리...
}
ex04
<%@page import="java.util.Date"%>
<%@ page 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">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2022. 6. 30. - 오전 10:38:10</title>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="httpRequest.js"></script>
<!--
js ajax
1. XMLHttpRequest 생성
2. onreadyStateChange 속성 - 콜백함수 등록
-->
</head>
<body>
<h3>ex04.jsp</h3>
처음 ex04.jsp 요청한 시간: <%= new Date().toLocaleString() %>
<br />
<input type="button" value="emp sal Top5" onclick="getTop()" />
<br />
<p id="demo"></p>
<script>
var timer;
function getTop(){
sendRequest("ex04_top5.jsp",null,callback,"GET");
timer = setTimeout(getTop,4000);
}
function callback(){
if(httpRequest.readyState == 4){ // 서버 요청 완료
if(httpRequest.status == 200){ // 응답 성공
$("#demo").html(httpRequest.responseText)
} else{
alert("에이작스 실패: " + httpRequest.status);
}
}
}
</script>
</body>
</html>
'JSP' 카테고리의 다른 글
[JSP] 구글 맵 api (0) | 2022.07.04 |
---|---|
[JSP] JSON (0) | 2022.07.01 |
[JSP] EmpDeptList를 MVC패턴으로 구현 (0) | 2022.06.29 |
[JSP] ServletContextListener 인터페이스 활용 방법 (0) | 2022.06.24 |
[JSP] MVC 패턴 (0) | 2022.06.23 |