option + Enter
Add Library → Server Runtime → Tomcat 추가
ajax.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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
// document.getElementById("b1")
// id가 b1 버튼을 찾아서 클릭했을 때 입력값으로 넣은 function(){함수처리부분}을 실행시킴
$('#b1').click(function() {
alert("alert 실행됨")
$.ajax({
url : "test.jsp",
data : {
test : $('#test').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
},
error : function(e) {
alert(e)
}
})
})
}) // $
</script>
</head>
<body>
<label for=test>ajax테스트:</label>
<input id="test">
<button id="b1" type="button" class="btn btn-dark">AjaxTest</button>
<label for=money>결제금액:</label>
<input id="money">
<br>
1)계좌이체,2)신용카드,3)휴대폰결제
<br>
<label for="what">결제수단 :</label>
<input id="what">
<button id="b2" type="button" class="btn btn-dark">기상청정보 받아오기</button>
<hr>
<label for="user">회원가입할Id :</label>
<input id="user">
<button id="b3" type="button" class="btn btn-dark">회언가입시 id중복체크</button>
<hr>
<label for="tel">인증받을 전화번호 입력 :</label>
<input id="tel">
<button id="b4" type="button" class="btn btn-dark">인증변호받기</button>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lime;"></div>
</body>
</html>
연결할 파일 test.jsp에 아래 코드를 입력한다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- test.jsp?test = 배고파 --%>
<%
String test = request.getParameter("test");
%>
AJAX 테스트 결과 : <%= test %>
결과창이다.
여기에 회원 ID 중복체크에 해당하는 코드도 작성해본다.
<%@ 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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
// document.getElementById("b1")
// id가 b1 버튼을 찾아서 클릭했을 때 입력값으로 넣은 function(){함수처리부분}을 실행시킴
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "test.jsp",
data : {
test : $('#test').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b1
$('#b3').click(function() {
alert("alert 실행됨III")
$.ajax({
url : "idCheck.jsp",
data : {
test : $('#user').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d3').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b3
}) // $
</script>
</head>
<body>
<label for=test>AJAX 테스트:</label>
<input id="test">
<button id="b1" type="button" class="btn btn-dark">AjaxTest</button>
<label for=money>결제금액:</label>
<input id="money">
<br>
1)계좌이체,2)신용카드,3)휴대폰결제
<br>
<label for="what">결제수단 :</label>
<input id="what">
<button id="b2" type="button" class="btn btn-dark">기상청정보 받아오기</button>
<hr>
<label for="user">회원가입할Id :</label>
<input id="user">
<button id="b3" type="button" class="btn btn-dark">회원가입시 id중복체크</button>
<hr>
<label for="tel">인증받을 전화번호 입력 :</label>
<input id="tel">
<button id="b4" type="button" class="btn btn-dark">인증번호받기</button>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lime;"></div>
</body>
</html>
연결할 idCheck.jsp파일에는 아래와 같이 작성해준다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String user = request.getParameter("user");
String result = "중복이 되지 않아 사용 가능함";
String[] list = {"root", "admin", "hong"};
for (String s : list){
if (s.equals(user)){
result = "중복이 되므로, 사용 불가";
break; //반복문의 break;
}
}
%><%= 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
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
// document.getElementById("b1")
// id가 b1 버튼을 찾아서 클릭했을 때 입력값으로 넣은 function(){함수처리부분}을 실행시킴
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "test.jsp",
data : {
test : $('#test').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b1
$('#b2').click(function() {
alert("alert 실행됨II")
$.ajax({
url : "money.jsp",
data : {
what : $('#what').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b2
$('#b3').click(function() {
alert("alert 실행됨III")
$.ajax({
url : "idCheck.jsp",
data : {
user : $('#user').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b3
$('#b4').click(function() {
alert("alert 실행됨IIII")
$.ajax({
url : "phone.jsp",
data : {
tel : $('#tel').val()
},
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 인증번호는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b4
}) // $
</script>
</head>
<body>
<label for=test>AJAX 테스트:</label>
<input id="test">
<button id="b1" type="button" class="btn btn-dark">AjaxTest</button>
<label for=money>결제금액:</label>
<input id="money">
<br>
1)계좌이체,2)신용카드,3)휴대폰결제
<br>
<label for="what">결제수단 :</label>
<input id="what">
<button id="b2" type="button" class="btn btn-dark">기상청정보 받아오기</button>
<hr>
<label for="user">회원가입할Id :</label>
<input id="user">
<button id="b3" type="button" class="btn btn-dark">회원가입시 id중복체크</button>
<hr>
<label for="tel">인증받을 전화번호 입력 :</label>
<input id="tel">
<button id="b4" type="button" class="btn btn-dark">인증번호받기</button>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lime;"></div>
</body>
</html>
연결할 파일 phone.jsp 코드
<%@page import="java.util.Random"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String tel = request.getParameter("tel");
String result = "222"; //인증문자
String pre = tel.substring(0,3); //010
switch(pre) {
case "010":
result = "100";
break;
case "011":
result = "111";
break;
}
Random r = new Random();
int post = r.nextInt(900) + 100; //0~899 -> 0~999
result += post; // result = result + post
%><%= result %>
공부할 것
XML과
<?xml version="1.0" encoding="UTF-8"?>
<result>
<item>
<rank>
<name>Uxia</name>
<tel>3752</tel>
</rank>
<rank>
<name>Noeh</name>
<tel>7653</tel>
</rank>
</item>
</result>
xml을 jsp로 불러오는 작업
ajax2.jsp 파일에 아래 코드를 작성해서 xml을 통째로 불러왔다.
<%@ 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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "data/rank.xml",
success : function(x) {
alert("받은 데이터는 " + x)
$('#d1').html("받은 데이터는 : " + x)
},
error : function(e) {
alert(e)
}
})
}) // b1
}) // $
</script>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">XML 예제</button><br>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lime;"></div>
</body>
</html>
다음으로 xml파일 안의 텍스트까지 불러오도록 한다.
<%@ 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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "data/rank.xml",
success : function(doc) {
alert("받은 데이터는 " + doc)
list = $(doc).find('rank') //배열 [rank, rank, rank], [rank]
alert(list.length + " " + list)
for (var i = 0; i < list.length; i++) {
name = $(list[i]).find('name').text() //<name>Uxia<name>
alert(name)
$('#d1').append("Name : " + name + "<br>")
}
},
error : function(e) {
alert(e)
}
})
}) // b1
}) // $
</script>
<style>
input {
background : yellow;
color : red;
}
</style>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">XML 예제</button><br>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lightyellow;"></div>
</body>
</html>
아래와같이 추가해주면 tel에 대한 정보도 불러올 수 있다.
실무에서 쓰이는 xml이 궁금할 때
mockaroo사이트에서 mock data를 만들어보면 된다.
여기서 자유롭게 설정 가능하다.
파일을 가져와서 보면 1000개의 목데이터를 가져온 걸 확인할 수 있다.
같은 방식으로 xml파일을 불러오면
<%@ 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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "data/dataset.xml",
success : function(doc) {
// alert("받은 데이터는 " + doc)
list = $(doc).find('rank') //배열 [rank, rank, rank], [rank]
alert(list.length + " " + list)
for (var i = 0; i < list.length; i++) {
first_name = $(list[i]).find('first_name').text() //<name>Uxia<name>
tel = $(list[i]).find('tel').text()
// alert(name)
console.log("이름은 " + first_name + ", 연락처는 " + tel + "<br>")
$('#d1').append("Name : " + first_name + ", 연락처는 " + tel + "<br>")
}
},
error : function(e) {
alert(e)
}
})
}) // b1
}) // $
</script>
<style>
input {
background : yellow;
color : red;
}
</style>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">XML 예제</button><br>
<hr>
<div id="d1" style="width: 400px; height: 25000px; background: lightyellow;"></div>
</body>
</html>
mock data로 json 파일도 다운받았다.
data 폴더에 파일을 추가해주고
ajax4.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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "data/MOCK_DATA.json",
success : function(doc) {
// alert("받은 데이터는 " + doc)
list = doc
for (var i = 0; i < list.length; i++) {
name = list[i].name
tel = list[i].tel
// alert(name)
$('#d1').append("Name : " + name + ", 연락처는 " + tel + "<br>")
}
},
error : function(e) {
alert(e)
}
})
}) // b1
}) // $
</script>
<style>
input {
background : yellow;
color : red;
}
</style>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">XML 예제</button><br>
<hr>
<div id="d1" style="width: 400px; height: 1500px; background: lightyellow;"></div>
</body>
</html>
https://news.jtbc.co.kr/Etc/RssService.aspx
JTBC 뉴스
news.jtbc.co.kr
이런식으로 신문사의 rss를 찾아서 코드에 연결할 수 있다.
ajax5.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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨I")
$.ajax({
url : "https://rss.hankyung.com/feed/it.xml",
success : function(doc) {
alert('한경 연결 성공')
},
error : function(e) {
alert('한경 연결 실패')
}
})
}) // b1
}) // $
</script>
<style>
input {
background : yellow;
color : red;
}
</style>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">XML 예제</button><br>
<hr>
<div id="d1" style="width: 400px; height: 1500px; background: lightyellow;"></div>
</body>
</html>
연결 실패는 신문사에서 외부 연결을 차단해서 그런 것 같다.
오류 해결 방안
<%@ 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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(function() {
$('#b1').click(function() {
alert("내가 호출되었어.!")
$.ajax({
url: "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Frss.hankyung.com%2Ffeed%2Fit.xml&api_key=rooa9cfdnkctmsnpiftxnozlzfyaunxvudzwajoq",
success: function(doc) {
list = doc.items //[{},{},{}]
alert('프락시 서버 연결 성공.@@@@@@@@>> ' + list.length)
for (var i = 0; i < list.length; i++) {
title = list[i].title
pubDate = list[i].pubDate
link = list[i].link
author = list[i].author
console.log(title+ ", " + pubDate + ", " + link + ", " + author)
//$('#d1').append(title+ ", " + pubDate + ", " + link + ", " + author + "<br>")
$('#d1').append("<a href=" + link + ">" + title + "</a><br>")
}
},
error: function(e) {
alert('프락시 서버 실패.@@@@@@@@')
} //error
}) //ajax
}) //b1
}) //$
</script>
<style>
input{
background: yellow;
color: red;
}
</style>
</head>
<body>
<button id="b1" class="mt-2 p-2 bg-primary text-white rounded">한경 기사 XML받아오자.</button>
<hr>
<div id="d1" style="width: 500px; height: 300px; background: lightyellow;">
</div>
</body>
</html>
AJAX 최종 확인 문제
drug.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="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
$(function() {
$('#b1').click(function() {
alert("alert 실행됨")
$.ajax({
url : "data/drug_data.json",
success : function(doc) { //[json, json, json]
list = doc
for (var i = 0; i < list.length; i++) {
id = list[i].id
name = list[i].name
company = list[i].company
code = list[i].code
// alert(name)
$('#d1').append("drug info : " + "<br>" + "ID : " + id + "<br>" + "Name : " + name + "<br>" + "Company : " + company + "<br>" + "Code : " + code + "<br>" + "<br>")
// 내 서버로 보내서 sql문 작성 후 db에 넣기
$.ajax({
url : "db2.jsp",
data : {
id : id,
name : name,
company : company,
code : code
},
success : function() {
console.log("DB Connected")
},
error : function() {
console.log("DB Disconnected")
}
})
}
},
error : function(e) {
alert(e)
} // error
}) // ajax
}) // b1
}) // $
</script>
<style>
input {
background : yellow;
color : red;
}
</style>
</head>
<body>
<button id="b1" type="button" class="btn btn-dark">Drug Information</button><br>
<hr>
<div id="d1" style="width: 400px; height: 1500px; background: lightyellow;"></div>
</body>
</html>
db2.jsp 파일 코드
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String id = request.getParameter("id");
String name = request.getParameter("name");
String company = request.getParameter("company");
String code = request.getParameter("code");
//db연결해서 sql만든 후, 전송!!!!
//1. 드라이버 설정
Class.forName("com.mysql.cj.jdbc.Driver");
//out객체: 내장된 객체, PrintWriter
out.print("1. 드라이버 설정 성공");
String url = "jdbc:mysql://localhost:3306/shop?serverTimezone=UTC";
String user = "root";
String password = "1234";
//2. db연결 - url(ip + port + db명), id, pw
//자동완성 DriverM ==> 컨트롤 + 스페이스바
//JSP에서 import단축키 : 컨트롤(cmd) + 쉬프트 + m
Connection con = DriverManager.getConnection(url, user, password); //Connection
out.print("2. db연결 성공");
//3. sql문 생성
String sql = "insert into drug values (?, ?, ?, ?)";
//위에 String은 자바에서는 sql문으로 인식 불가
//sql문에 해당하는 부품으로 만들어주어야 한다.
//PreparedStatement --- sql
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, company);
ps.setString(4, code);
out.print("3. sql문 생성 성공");
//4. sql문 전송
ps.executeUpdate();
out.print("4. sql문 전송 성공");
ps.close();
con.close();
%>
DB 출력 결과
브라우저 출력 결과
'Back > Spring' 카테고리의 다른 글
Day41_[Mac OS]Spring/STS 설치 및 세팅 (0) | 2023.06.30 |
---|---|
Day33_DAO+VO(DTO)로 회원가입 페이지 생성(DB에 연결) with Exception(오류코드) (0) | 2023.06.21 |
Day24_CRUD jsp 완성 과제 (1) | 2023.06.15 |
Day20_#9 IntelliJ 스프링부트 롬복과 리팩터링 (0) | 2023.06.08 |
Day17_#7_IntelliJ 스프링부트 JPA로 DB에 데이터 생성 (0) | 2023.06.01 |