[실습] Product
Product Table Create
create table product(
num number primary key,
name varchar2(30) not null,
price number(9) not null,
stock number(9) not null,
origin varchar2(30) not null,
reg_date date not null
);
create sequence product_seq;
JavaScript
window.onload=function(){
const myForm = document.getElementById('myForm');
myForm.onsubmit = function(){
const items = document.querySelectorAll('input[type="text"], input[type="number"]');
for(let i = 0; i < items.length; i++){
if(items[i].value.trim() == ''){
const label = document.querySelector('label[for="' + items[i].id + '"]');
alert(label.textContent + ' 항목은 필수 입력입니다.');
items[i].value ='';
items[i].focus();
return false;
}
}
};
};
StyleSheet
@charset "UTF-8";
* {
font-family: sans-serif;
}
body{
padding: 0;
margin: 0;
}
.page-main{
width: 800px;
margin: 0 auto;
}
.result-display{
width: 400px;
height: 200px;
margin: 50px auto;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
.align-center{
text-align: center;
}
.align-right{
text-align: right;
}
table{
width: 100%;
border: 1px solid #000;
border-collapse: collapse;
margin-top: 5px;
}
table td, table th{
border: 1px solid #000;
padding: 5px;
}
form{
width: 500px;
margin: 0 auto;
border: 2px solid #000;
padding: 10px 10px 10px 30px;
}
ul{
list-style: none;
}
label{
width: 100px;
float: left;
font-size: 15px;
font-family: sans-serif;
}
.button{
border: 2px solid #b5b4b8;
background-color: white;
border-radius: 20px;
cursor: pointer;
}
.button:hover {
border-radius: 20px;
background-color: #eeedf0;
}
a{
text-decoration-line: none;
color: black;
}
a:hover {
color: #cebdff;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product Insert</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="page-main">
<h2>Product Insert</h2>
<form action="insertTest.jsp" id="myForm" method="post">
<ul>
<li>
<label for="name">Name</label>
<input type="text" name="name" id="name">
</li>
<li>
<label for="price">Price</label>
<input type="number" name="price" id="price" >
</li>
<li>
<label for="stock">Stock</label>
<input type="number" name="stock" id="stock">
</li>
<li>
<label for="origin">Origin</label>
<input type="text" name="origin" id="origin">
</li>
</ul>
<div class="align-center">
<input type="submit" class="button" value="Insert">
<input type="button" class="button" value="List" onclick="location.href='selectTest.jsp'">
</div>
</form>
</div>
</body>
</html>
Product Insert JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product Insert Process</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
int price = Integer.parseInt(request.getParameter("price"));
int stock = Integer.parseInt(request.getParameter("stock"));
String origin = request.getParameter("origin");
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try{
conn = DBUtil.getConnection();
sql = "INSERT INTO product (num,name,price,stock,origin,reg_date) VALUES(product_seq.nextval,?,?,?,?,SYSDATE)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2,price);
pstmt.setInt(3,stock);
pstmt.setString(4,origin);
pstmt.executeUpdate();
%>
<div class="result-display">
<div class="align-center">
Product Insert Complete!<p></p>
<input type="button" class="button" value="List" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
} catch(Exception e){
%>
<div class="result-display">
<div class="align-center">
Product Insert Uncompleted. Error has occurred.<p></p>
<input type="button" class="button" value="Insert" onclick="location.href='insertTestForm.jsp'">
</div>
</div>
<%
e.printStackTrace();
} finally{
DBUtil.executeClose(null, pstmt, conn);
}
%>
</body>
</html>
Product List
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product List</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
</head>
<body class="page-main">
<h2>Product List</h2>
<div class="align-right">
<input type="button" class="button" value="Insert Product" onclick="location.href='insertTestForm.jsp'">
</div>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try{
conn = DBUtil.getConnection();
sql = "SELECT * FROM product ORDER BY num DESC";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
%>
<table>
<tr>
<th>제품 번호</th>
<th>제품명</th>
<th>제조사</th>
<th>등록일</th>
</tr>
<%
while(rs.next()){
int num = rs.getInt("num");
String name = rs.getString("name");
String origin = rs.getString("origin");
Date reg_date = rs.getDate("reg_date");
%>
<tr>
<td><%= num %></td>
<td><a href="detailTest.jsp?num=<%= num %>"><%= name %></a></td>
<td><%= origin %></td>
<td><%= reg_date %></td>
</tr>
<%
}
%>
</table>
<%
}catch(Exception e){
%>
<div class="result-display">
<span>오류 발생!</span>
</div>
<%
e.printStackTrace();
}finally{
DBUtil.executeClose(rs, pstmt, conn);
}
%>
</body>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 상세 정보 불러오기</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
</head>
<body>
<div class="page-main">
<h2>상품 상세 정보</h2>
<%
int num = Integer.parseInt(request.getParameter("num"));
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try{
conn = DBUtil.getConnection();
sql = "SELECT * FROM product WHERE num = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()){
String name = rs.getString("name");
int price = rs.getInt("price");
int stock = rs.getInt("stock");
String origin = rs.getString("origin");
Date reg_date = rs.getDate("reg_date");
%>
<ul>
<li>제품 번호 : <%= num %></li>
<li>제품명 : <%= name %></li>
<li>제품 가격 : <%= String.format("%,d원", price) %></li>
<li>제품 재고 : <%= stock %>개</li>
<li>제조사 : <%= origin %></li>
<li>제품 등록일 : <%= reg_date %></li>
</ul>
<hr width="100%" size="1" noshade="noshade">
<div class="align-right">
<input type="button" value="Update" class="button" onclick="location.href='updateTestForm.jsp?num=<%=num%>'">
<input type="button" value="Delete" class="button" id ="delete_btn">
<input type="button" value="List" class="button" onclick="location.href='selectTest.jsp'">
</div>
<script type="text/javascript">
let delete_btn = document.getElementById('delete_btn');
delete_btn.onclick = function(){
let choice = confirm('해당 제품을 삭제하시겠습니까?');
if(choice){
location.replace('deleteTest.jsp?num=<%=num%>');
}
};
</script>
<%
}else{
%>
<div class="result-display">
<div class="align-center">
제품 상세 정보가 존재하지 않습니다.<p>
<input type="button" value="List" class="button" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
}
} catch(Exception e){
e.printStackTrace();
%>
<div class="result-display">
<div class="align-center">
오류가 발생하여 제품 상세 정보를 불러오는데 실패하였습니다.<p>
<input type="button" value="List" class="button" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
} finally{
DBUtil.executeClose(rs, pstmt, conn);
}
%>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>제품 정보 수정하기</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="page-main">
<h2>제품 정보 수정하기</h2>
<%
int num = Integer.parseInt(request.getParameter("num"));
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try{
conn = DBUtil.getConnection();
sql = "SELECT * FROM product WHERE num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,num);
rs = pstmt.executeQuery();
if(rs.next()){
String name = rs.getString("name");
int price = rs.getInt("price");
int stock = rs.getInt("stock");
String origin = rs.getString("origin");
%>
<form action="updateTest.jsp" id="myForm" method="post">
<input type="hidden" name="num" value="<%= num %>">
<ul>
<li>
<label for="name">제품명</label>
<input type="text" name="name" id="name" value="<%= name %>">
</li>
<li>
<label for="price">제품 가격</label>
<input type="number" name="price" id="price" value="<%= price %>">
</li>
<li>
<label for="stock">제품 재고</label>
<input type="number" name="stock" id="stock" value="<%= stock %>">
</li>
<li>
<label for="origin">제조사</label>
<input type="text" name="origin" id="origin" value="<%= origin %>">
</li>
</ul>
<div class="align-center">
<input type="submit" class="button" value="수정">
<input type="button" class="button" value="목록" onclick="location.href='selectTest.jsp'">
</div>
</form>
<%
} else{
%>
<div class="result-display">
<div class="align-center">
오류가 발생햇습니다. 수정할 제품 정보 호출에 실패하였습니다.<p>
<input type="button" class="button" value="목록" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
}
} catch(Exception e) {
%>
<div class="result-display">
<div class="align-center">
오류가 발생햇습니다. 수정할 제품 정보 호출에 실패하였습니다.<p>
<input type="button" class="button" value="목록" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
e.printStackTrace();
} finally{
DBUtil.executeClose(rs, pstmt, conn);
}
%>
</div>
</body>
</html>
Product Info Update JSP
<%@page import="java.sql.PreparedStatement"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>제품 정보 수정하기</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
int num = Integer.parseInt(request.getParameter("num"));
String name = request.getParameter("name");
int price = Integer.parseInt(request.getParameter("price"));
int stock = Integer.parseInt(request.getParameter("stock"));
String origin = request.getParameter("origin");
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
conn = DBUtil.getConnection();
sql = "UPDATE product SET name=?, price=?, stock=?, origin=? WHERE num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2, price);
pstmt.setInt(3, stock);
pstmt.setString(4, origin);
pstmt.setInt(5, num);
pstmt.executeUpdate();
%>
<div class="result-display">
<div class="align-center">
제품 정보가 수정되었습니다.<p>
<input type="button" class="button" value="제품 정보" onclick="location.href='detailTest.jsp?num=<%= num %>'">
</div>
</div>
<%
} catch (Exception e) {
%>
<div class="result-display">
<div class="align-center">
오류가 발생했습니다. 해당 제품 정보 호출에 실패하였습니다.<p>
<input type="button" class="button" value="목록" onclick="location.href='updateTestForm.jsp?num=<%= num%>'">
</div>
</div>
<%
e.printStackTrace();
} finally {
DBUtil.executeClose(null, pstmt, conn);
}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>등록 제품 삭제하기</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<%
int num = Integer.parseInt(request.getParameter("num"));
%>
<div class="page-main">
<h2>제품 삭제</h2>
<form action="deleteTest.jsp" id="myForm">
<input type="hidden" name="num" value="<%= num%>">
<div class="align-center">
<p class="align-center">
<span>해당 제품을 삭제하시겠습니까?</span>
</p>
<br>
<input type="submit" class="button" value="삭제">
<input type="button" value="목록" class="button" onclick="location.href='selectTest.jsp'">
</div>
</form>
</div>
</body>
</html>
Product Delete JSP
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 삭제 처리</title>
<link rel="stylesheet" href="../css/style2.css" type="text/css">
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
int num = Integer.parseInt(request.getParameter("num"));
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
conn = DBUtil.getConnection();
sql = "DELETE FROM product WHERE num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.executeUpdate();
%>
<div class="result-display">
<div class="align-center">
제품 삭제가 완료되었습니다.<p>
<input type="button" class="button" value="목록" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
} catch (Exception e) {
%>
<div class="result-display">
<div class="align-center">
오류가 발생하였습니다. 제품 삭제에 실패하였습니다.<p>
<input type="button" class="button" value="목록" onclick="location.href='selectTest.jsp'">
</div>
</div>
<%
e.printStackTrace();
} finally {
DBUtil.executeClose(null, pstmt, conn);
}
%>
</body>
</html>

Ajax
Ajax 개요
AJAX(AJAX = Asynchronous JavaScript and XML) 비동기적으로 서버의 데이터를 호출하는 방식을 의미한다. Ajax를 사용하면 페이지를 전환하지 않고 서버에서 데이터를 받아와 사용자에게 보여줄 수 있다.
jQuery Ajax 메서드
$.ajax(options);
$.ajax(url,options);
Ajax 메서드의 옵션
옵션 속성 이름 | 설명 | 자료형 |
---|
async | 동기, 비동기를 지정 | Boolean |
complete(jqXHR,textStatus) | Ajax 완료 이벤트 핸들러를 지정 | Function |
data | 요청 매개 변수를 지정 | Object,String |
error(jqXHR,textStatus,errorThrown) | Ajax 실패 이벤트 핸들러를 지정 | Function |
jsonp | JSONP 매개 변수 이름을 지정 | String |
jsonpCallback | JSONP 콜백 함수 이름을 지정 | String,Function |
success(data,textStatus,jqXHR) | Ajax 성공 이벤트 핸들러를 지정 | Function,Array |
timeout | 만료 시간을 지정 | Number |
type | ‘GET’ 또는 ‘POST’를 지정 | String |
url | 대상 URL을 지정 | String |
jQuery Ajax 부가 메서드
메서드 이름 | 설명 |
---|
$.get() | get 방식으로 Ajax를 수행 |
$.post() | post 방식으로 Ajax를 수행 |
$.getJSON() | get 방식으로 Ajax를 수행해 JSON 데이터를 가져옴 |
$.getScript() | get 방식으로 Ajax를 수행해 Script 데이터를 가져옴 |
$(selector).load() | Ajax를 수행한 후에 선택자로 선택한 문서 객체 안에 응답받을 문자열을 넣음 |
jQuery Ajax 보조 메서드
메서드 | 이름설명 |
---|
serialize() | 입력 양식의 내용을 요청 매개 변수 문자열로 만듬 |
serializeArray() | 입력 양식의 내용을 객체로 만듬 |
$.param() | 객체의 내용을 요청 매개 변수 문자열로 만듬 |
다양한 타입들 Ajax 실습
myString.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
Hello JSP!
Ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery를 이용한 비동기 통신 구현</title>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url:'myString.jsp',
success: function(param){
$('body').append(param);
}
});
});
</script>
</head>
<body>
</body>
</html>

myParam.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
%>
이름은 <%= name %>이고 나이는 <%= age %>살 입니다.
Ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery를 이용한 비동기 통신 구현</title>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : 'myParam.jsp',
data : {
name : "홍길동",
age : 21
},
success : function(param){
$('body').append(param);
}
});
});
</script>
</head>
<body>
</body>
</html>

myXML.jsp
<%@ page language="java" contentType="text/xml; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<?xml version="1.0" encoding="UTF-8"?>
<peolpe>
<person>
<name>홍길동</name>
<job>형사</job>
<age>20</age>
</person>
<person>
<name>박문수</name>
<job>교사</job>
<age>40</age>
</person>
</peolpe>
Ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery를 이용한 비동기 통신 구현</title>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url : 'myXML.jsp',
success : function(param){
$(param).find('person').each(function(){
let name ='<li>' + $(this).find('name').text() + '</li>';
let job = '<li>' + $(this).find('job').text() + '</li>';
let age = '<li>' + $(this).find('age').text() + '</li>';
$('body').append('<ul>'+name+job+age+'</ul>');
});
}
});
});
</script>
</head>
<body>
</body>
</html>

myJSON.jsp
데이터 타입을 지정 안 하면 단순 텍스트로 읽어버림, JSON은 객체로 인식해줘야 하기 때문에 datatype을 알려줌
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
[{
"name" : "장영실",
"job" : "과학자",
"age" : 50
},{
"name" : "김유신",
"job" : "군인",
"age" : 30
}]
Ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery를 이용한 비동기 통신 구현</title>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'myJSON.jsp',
dataType : 'json',
success : function(param){
$(param).each(function(index,item){
let output = '';
output += '<div>';
output += '<h1>' + item.name + '</h1>';
output += '<p>' + item.job + '</p>';
output += '<p>' + item.age + '</p>';
output += '</div>';
$('#output').append(output);
});
}
});
});
</script>
</head>
<body>
<div id="output">
</div>
</body>
</html>

ID 중복 체크 하기
Create People Table
create table people(
id varchar2(10) primary key,
name varchar2(30) not null,
job varchar2(30) not null,
address varchar2(60) not null,
blood_type varchar2(2) not null,
reg_date date not null
);
INSERT INTO people VALUES ('lavender','김제니','가수','서울시','B',SYSDATE);
Confirm ID JSP
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import="kr.util.DBUtil" %>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try{
conn = DBUtil.getConnection();
sql = "SELECT id FROM people WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()){
%>
{"result" : "idDuplicated"}
<%
} else {
%>
{"result" : "idNotFound"}
<%
}
}catch(Exception e){
%>
{"result" : "failure"}
<%
e.printStackTrace();
} finally{
DBUtil.executeClose(rs, pstmt, conn);
}
%>
Confirm ID HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>아이디 중복 체크</title>
<style>
ul{
padding: 0;
margin: 0;
list-style: none;
}
ul li{
padding: 0;
margin: 0 0 0 10px 0;
}
label{
width: 100px;
float: left;
}
</style>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
let count = 0;
$('#confirm_id').click(function(){
if($('#id').val().trim()==''){
alert('ID를 입력하세요.');
$('#id').val('').focus();
return;
}
$.ajax({
url:'confirmId.jsp',
type : 'post',
dataType : 'json',
data : {id:$('#id').val()},
success : function(param){
if(param.result == 'idDuplicated'){
count = 0;
$('#id_signed').text('이미 등록된 아이디입니다.').css('color', 'red');
$('#id').val('').focus();
} else if(param.result == 'idNotFound'){
count = 1;
$('#id_signed').text('사용 가능한 아이디입니다.').css('color', 'black');
} else{
count = 0;
alert('아이디 중복 체크 오류!');
}
},
error : function(){
count = 0;
alert('Network Error Occurred');
}
});
});
$('#insert_form #id').keydown(function(){
count = 0;
$('#id_signed').text('');
});
$('#insert_form').submit(function(){
if($('#id').val().trim()==''){
alert('아이디를 입력해주세요.');
$('#id').val('').focus();
return false;
}
if(count == 0){
alert('아이디 중복체크는 필수입니다.');
return false;
}
});
});
</script>
</head>
<body>
<form id="insert_form" action="register.jsp" method="post">
<fieldset>
<legend>회원 가입</legend>
<ul>
<li>
<label for="id">아이디</label>
<input type="text" id="id" name="id">
<input type="button" id="confirm_id" value="아이디 중복 체크" >
<span id="id_signed"></span>
</li>
<li>
<input type="submit" value="전송">
</li>
</ul>
</fieldset>
</form>
</body>
</html>

Member Register & List
Member HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 목록</title>
<style>
form{
width: 500px;
margin: 10px auto;
}
ul{
padding: 0;
margin: 0;
list-style: none;
}
ul li{
padding: 0;
margin: 0 0 10px 0;
}
label{
width: 150px;
float: left;
}
table{
border: 1px solid gray;
width: 500px;
margin: 0 auto;
border-collapse: collapse;
}
td{
border: 1px solid gray;
padding: 10px;
}
</style>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function selectList(){
$.ajax({
url:'getPeopleJSON.jsp',
dataType:'json',
success : function(param){
$('#output').empty();
$(param).each(function(index,item){
let output = '';
output += '<tr>';
output += '<td>' + item.id+'</td>';
output += '<td>' + item.name+'</td>';
output += '<td>' + item.job+'</td>';
output += '<td>' + item.address+'</td>';
output += '<td>' + item.blood_type+'</td>';
output += '<td>' + item.reg_date+'</td>';
output += '</tr>';
$('#output').append(output);
});
},
error : function(){
alert('Network Error Occurred');
}
});
};
$('#insert_form').submit(function(event){
let input_data = $(this).serialize();
$.ajax({
url : 'insertPerson.jsp',
type : 'post',
data : input_data,
dataType : 'json',
success : function(param){
if(param.result == 'success'){
alert('회원 가입에 성공했습니다.');
$('#insert_form input[type="text"]').val('');
selectList();
} else{
alert('회원 가입 도중에 오류가 발생했습니다.');
}
},
error : function(param){
alert('Network Error Occurred');
}
});
event.preventDefault();
});
selectList();
});
</script>
</head>
<body>
<form id="insert_form">
<fieldset>
<legend>회원 등록</legend>
<ul>
<li>
<label for="id">아이디</label>
<input type="text" id="id" name="id">
</li>
<li>
<label for="name">이름</label>
<input type="text" id="name" name="name">
</li>
<li>
<label for="job">직업</label>
<input type="text" id="job" name="job">
</li>
<li>
<label for="address">주소</label>
<input type="text" id="address" name="address">
</li>
<li>
<label for="blood_type">혈액형</label>
<input type="text" id="blood_type" name="blood_type">
</li>
<li>
<input type="submit" value="추가">
</li>
</ul>
</fieldset>
</form>
<table id="output">
</table>
</body>
</html>
Member Insert JSP
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String job = request.getParameter("job");
String address = request.getParameter("address");
String blood_type = request.getParameter("blood_type");
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
conn = DBUtil.getConnection();
sql = "INSERT INTO people(id,name,job,address,blood_type,reg_date) VALUES(?,?,?,?,?,SYSDATE)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, name);
pstmt.setString(3, job);
pstmt.setString(4, address);
pstmt.setString(5, blood_type);
pstmt.executeUpdate();
%>
{"result" :"success"}
<%
} catch(Exception e){
%>
{"result":"failure"}
<%
e.printStackTrace();
}finally{
DBUtil.executeClose(null, pstmt, conn);
}
%>
Get Member List JSP
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
[<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try {
conn = DBUtil.getConnection();
sql = "SELECT * FROM people ORDER BY reg_date DESC";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String job = rs.getString("job");
String address = rs.getString("address");
String blood_type = rs.getString("blood_type");
String reg_date = rs.getString("reg_date");
if(rs.getRow() > 1){
out.println(",");
}
%>
{
"id":"<%=id%>",
"name":"<%=name%>",
"job":"<%=job%>",
"address" :"<%=address%>",
"blood_type":"<%=blood_type%>",
"reg_date":"<%=reg_date%>"
}
<%
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.executeClose(rs, pstmt, conn);
}
%>]
