JSP/이론
Ajax 아작스
SEOKIHOUSE
2023. 6. 5. 18:16
앞의 수업에서는
이렇게 하면 페이지가 넘어간다
이렇게 한 페이지에 하려면 어떻게 하느냐 Ajax를 써야한다 아작아작스~
아래 페이지 참고해서 보자
코딩교육 티씨피스쿨
4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등
tcpschool.com
AJAX Introduction
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
- responseText 서버로 부터 받아서 적으려고 한다
- false 동기 // 동기식은 요청 후 응답을 받아야지만 다음 동작이 이루어지고
- true 비동기통신 // 비동기식에서는 요청을 보낸 후 응답과는
상관없이 동작하는 방식이다. 이러한 이유때문에 http 전송 중에도 클라이언트가 웹 어플리케이션과 상호작용을 할 수
있는 것이다. - <false>
순서대로 진행되는 것 - <true>
서버에서 응답이 와야지 기다려야한다 ==아래는 thread.sleep(2000)이라 2초기다려야하는데
밑에 있는건(->내가 먼저 나올까?) 안기다리고 바로 처리
<%@ 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>
</head>
<body>
<button onclick="loadDoc()">load독 실행</button>
<div id="demo">여기 응답텍스트가 나옴</div>
<div id="demo2">여기 응답2텍스트가 나옴</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "DemoServlet", false);
xhttp.send();
document.getElementById("demo2").innerHTML = "내가 먼저 나올까?";
}
</script>
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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("/DemoServlet")
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DemoServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf8");
PrintWriter pw = response.getWriter();
try {
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
pw.print("응답: hello~Ajax!");
}
}
이제 아작스를 써보자
- Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있다
즉 Ajax를 이용하면 백그라운드 영역에서 서버와 통신하여, 그 결과를 웹 페이지의 일부분에만 표시할 수 있다.
여기서 form안쓰는이유는 폼쓰면 페이지가 넘어가서 그렇다 ㅇㅋ?
<%@ 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>
window.onload = function() {
const num1 = document.querySelector("input[name='num1']");
const num2 = document.querySelector("input[name='num2']");
const result = document.querySelector("input[name='result']");
const btns = document.getElementById("btn");
btns.addEventListener("click",loadDoc);
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
result.value = this.responseText;
}
xhttp.open("GET", "ajaxspracticeServlet?num1="+num1.value + "&num2=" + num2.value, false);
xhttp.send();
}
}
</script>
</head>
<body>
<h1>아작스연습 practice</h1>
<hr>
<input type="text" name="num1" id="nu1" value="" placeholder="input num1">+
<input type="text" name="num2" id="nu2" value="" placeholder="input num2">
<button id ="btn">=</button>
<input type="text" name="result" value="">
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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("/ajaxspracticeServlet")
public class ajaxspracticeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ajaxspracticeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
int intnum1 = Integer.parseInt(num1);
int intnum2 = Integer.parseInt(num2);
int result = intnum1 + intnum2;
PrintWriter pw = response.getWriter();
pw.print(result);
}
}
- 가위바위보 만들어보기(클릭시 랜덤으로 나온다)
<%@ 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>
window.onload = function() {
const buttons = document.querySelector("#btn");
const imgdivs = document.querySelector("#imgdiv");
buttons.addEventListener("click", f);
function f() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
imgdivs.innerHTML = this.responseText;
}
xhttp.open("GET", "ajaxspracticeServlet2",true);
xhttp.send();
}
}
</script>
</head>
<body>
<h1>Ajax Test</h1>
<hr>
<button id="btn">서버야.. 내가 뭘 내는게 좋을까?</button>
<div id="imgdiv"></div>
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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("/ajaxspracticeServlet2")
public class ajaxspracticeServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
int ranNum = (int)(Math.random() * 3) + 1;
if (ranNum == 1) {
pw.print("<img src='img/가위.PNG'>");
} else if (ranNum == 2) {
pw.print("<img src='img/바위.PNG'>");
} else if (ranNum == 3) {
pw.print("<img src='img/보.PNG'>");
}
}
}
- 문제) aaa = 중복된 아이디 bbb = 사용가능한 아이디
- 헷갈린부분!! >> 값 안가져와서 실행이 안됐따..
+ input은 쿼리스트림으로 값을 적어줘야한다!!
<%@ 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>
window.onload = function() {
let button = document.querySelector("#checkid");
const msg = document.querySelector("#message");
const ids = document.querySelector("input[name='ids']");
button.addEventListener("click", f);
function f() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
msg.innerHTML = this.responseText;
}
xhttp.open("GET", "ajaxspracticeServlet3?ids=" + ids.value, true)
xhttp.send();
}
}
</script>
</head>
<body>
<input type="text" name="ids" placeholder = "input id">
<button id = "checkid">중복확인</button>
<div id="message"></div>
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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("/ajaxspracticeServlet3")
public class ajaxspracticeServlet3 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//받는거
String id= request.getParameter("ids");
//보내는거
PrintWriter pw = response.getWriter();
String result="";
if(id.equals("aaa")) {
result = "중복된 아이디 입니다";
}else if(id.equals("bbb")) {
result ="사용 가능한 아이디 입니다";
}
pw.print("입력하신 아이디는 " +result);
}
}