<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>할 일 목록(TodoList)</title>
<link rel="stylesheet" href="https://unpkg.com/bootstrap@5.2.3/dist/css/bootstrap.min.css">
<style>
body{
margin:0;
padding:0;
font-family:sans-serif;
}
.title{
text-align:center;
font-weight:bold;
font-size:20pt;
}
.todo-done{
text-decoration:line-through;
}
.container{
padding:10px;
}
.pointer{
cursor:pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="card card-body">
<div class="title">할 일 목록(TodoList)</div>
</div>
<div class="card card-defalut">
<div class="card-body">
<div class="row mb-3">
<div class="col">
<div class="input-group">
<input type="text" class="form-control"
placeholder="할 일을 여기에 입력!" id="todo"> <span
class="btn btn-primary input-group-addon" id="add_btn">추가</span>
</div>
</div>
</div>
<div class="row">
<div class="cil">
<ul class="list-group" id="list"></ul>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="../js/jquery-3.7.1.min.js">
</script>
<script type="text/javascript">
//목록 처리
function selectList(){
//서버와 통신
$.ajax({
url:'getTodoList.jsp',
dataType:'json',
success:function(param){
$('#list').empty();
$(param).each(function(index, item){
let output = ''; // output 변수 초기화
if(item.completed){
output += '<li class="list-group-item list-group-item-success">';
output += '<span class="pointer todo-done check-btn" id="' + item.id + '" data-check="' + item.completed + '">' + item.todo + ' (완료)</span>';
} else {
output += '<li class="list-group-item">';
output += '<span class="pointer check-btn" id="' + item.id + '" data-check="' + item.completed + '">' + item.todo + ' (작성일:' + item.created + ')</span>';
}
output += '<span class="float-end badge bg-secondary pointer delete-btn" id="' + item.id + '">삭제</span>';
output += '</li>';
$('#list').append(output);
});
},
error:function(){
alert('네트워크 오류 발생!');
}
});
}
//초기 데이터 설정
selectList();
//등록 처리 함수
function addTodo(){
if($('#todo').val().trim()==''){
alert('할 일을 입력하세요');
$('#todo').val('').focus();
return;
}
//서버와 통신
$.ajax({
url:'insertTodo.jsp',
type:'post',
data:{todo:$('#todo').val()},
dataType:'json',
success:function(param){
if(param.result == 'success'){//등록성공
//입력창 초기화
$('#todo').val('');
//목록 호출
selectList();
}else{//등록실패
alert('할 일 등록 오류 발생');
}
},
error:function(){
alert('네트워크 오류 발생');
}
});
}
//등록 key 이벤트 연결
$('#todo').keydown(function(event){
if(event.keyCode == 13){//13번이 엔터키를 치는 경우임.
addTodo();
}
});
//등록 클릭 이벤트 연결
$('#add_btn').click(function(){
addTodo();
});
//삭제 이벤트 연결
$(document).on('click','.delete-btn',function(){
//서버와 통신
$.ajax({
url:'deleteTodo.jsp',
type:'post',
data:{id:$(this).attr('id')},
dataType:'json',
success:function(param){
if(param.result=='success'){
//목록 호출
selectList();
}else{
alert('할 일 삭제 오류 발생');
}
},
error:function(){
alert('네트워크 오류 발생');
}
});
});
//할 일 체크 이벤트 연결
$(document).on('click','.check-btn',function(){
//서버와 통신
$.ajax({
url:'updateTodo.jsp',
type:'post',
data:{id:$(this).attr('id'),
completed:$(this).attr('data-check')},
dataType:'json',
success:function(param){
if(param.result =='success'){
//목록 호출
selectList();
}else{
//할일 체크/해제 실패
alert('할 일 체크 오류 발생');
}
},
error:function(){
alert('네트워크 오류 발생');
}
});
});
</script>
</body>
</html>
table.sql
create table todo(
id number primary key,
todo varchar2(150) not null,
created date default sysdate not null,
completed number(1) default 0 not null -- 할 일 수행 여부 0이면 미완료, 1이면 완료
);
create sequence todo_seq;
todoList.html
1
insertTodo.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 todo = request.getParameter("todo");
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try{
//Connection 객체 반환
conn = DBUtil.getConnection();
//SQL문 작성
sql = "INSERT INTO todo (id, todo) VALUES (todo_seq.nextval, ?)";
//JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
//?에 바인딩
pstmt.setString(1,todo);
//JDBC 수행 4단계 :SQL문 실행
pstmt.executeUpdate();
%>
{"result" : "success"}
<%
}catch(Exception e){
%>
{"result": "failure"}
<%
e.printStackTrace();
}finally{
//자원정리
DBUtil.executeClose(null, pstmt, conn);
}
%>
getTodoList.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"%>
<%@ page import = "java.util.Date" %>
[<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try{
//Connection 객체 반환
conn =DBUtil.getConnection();
//sql문작성
sql = "SELECT * FROM todo ORDER BY id DESC";
//JDBC 수행 3단계 :PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
//JDBC 수행 4단계 : SQL문 작성
rs = pstmt.executeQuery();
while(rs.next()){
int id =rs.getInt("id");
String todo = rs.getString("todo");
Date created = rs.getDate("created");
int completed = rs.getInt("completed");
if(rs.getRow()>1) out.print(",");
%>
{
"id":<%=id %>,
"todo": "<%= todo %>",
"created": "<%= created %>",
"completed":<%= completed %>
}
<%
}
}catch(Exception e){
e.printStackTrace();
}finally{
//자원정리
DBUtil.executeClose(rs, pstmt, conn);
}
%>]
deleteTodo.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");
//전송된 데이터 반환
int id = Integer.parseInt(request.getParameter("id"));
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try{
//커넥션 객체 반환
conn=DBUtil.getConnection();
//sql작성
sql = "DELETE FROM todo WHERE id=?";
//JDBD수행3단계
pstmt = conn.prepareStatement(sql);
//?데이터 바인딩
pstmt.setInt(1,id);
//JDBC수행 4단계
pstmt.executeUpdate();
%>
{"result": "success"}
<%
}catch(Exception e){
%>
{"result":"failure"}
<%
e.printStackTrace();
}finally{
DBUtil.executeClose(null, pstmt, conn);
}
%>
updateTodo.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");
//전송된 데이터 반환
int id = Integer.parseInt(request.getParameter("id"));
int completed = Integer.parseInt(request.getParameter("completed"));
if(completed ==0) completed = 1;
else completed = 0;
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try{
//Connection 객체 반환
conn = DBUtil.getConnection();
//SQL문 작성
sql = "UPDATE todo SET completed =? WHERE id=?";
//JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
//?데이터 바인딩
pstmt.setInt(1,completed);
pstmt.setInt(2,id);
//JDBC 수행 4단계
pstmt.executeUpdate();
%>
{"result":"success"}
<%
}catch(Exception e){
%>
{"result":"failure"}
<%
e.printStackTrace();
}finally{
DBUtil.executeClose(null, pstmt, conn);
}
%>