본문 바로가기
학원/servlet jsp

11.9일 (db연동 - 게시판 / [실습] 상품 목록)

by 쿠룽지 2023. 11. 9.
728x90
반응형
728x90

 

 

11.8일 selectTest.jsp 에서 명시한 <td><a href="detailTest.jsp?num=<%= num %>"><%= title %></a></td>

부분의 detailTest.jsp 상세페이지 부분 부터 시작

 

 

detailTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Date" %> <%-- java.util이 아니라 java.sql.Date --%>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 상세 정보 보기</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="page-main">
	<h2>글 상세정보</h2>
	<%-- pk(num)를 전달해서 한 건의 정보를 가져오려고 함 --%>
<%
	//get방식이라 setCharacterEncoding 생략 가능 (기본적으로 get방식)
	int num = Integer.parseInt(request.getParameter("num"));
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = null;
	
	try{
		//JDBC 수행 1단계 : 드라이버 로드
		Class.forName(driverName);
		//JDBC 수행 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		//SQL문 작성
		sql = "SELECT * FROM tboard WHERE num=?";
		
		//JDBC 수행 3단계 : PreparedStatement 객체 생성
		pstmt = conn.prepareStatement(sql);
		
		//?에 데이터 바인딩
		pstmt.setInt(1, num);
		
		//JDBC 수행 4단계 : SQL문 실행
		rs = pstmt.executeQuery();
		if(rs.next()){// pk라 명백하게 1건이기 때문에 행 안에 진입시키기만 하면됨 (num이 조작될 경우 else로 빠지게/ 고의로 num=234234 이렇게 칠때)
			String name = rs.getString("name");
			String title = rs.getString("title");
			String content = rs.getString("content");
			Date reg_date = rs.getDate("reg_date");
%>
		<ul>
			<li>글번호 : <%= num %></li>
			<li>제목 : <%= title %></li>
			<li>작성자 : <%= name %></li>
			<li>작성일 : <%= reg_date %></li>
		</ul>
		<hr width="100%" size="1" noshade="noshade">
		<p>
			<%= content %>
		</p>
		<hr width="100%" size="1" noshade="noshade">
		<div class="align-right">
			<%-- 하나의 글만 수정/ 삭제할 수 있게 get방식으로 param 넘기기 --%>
			<input type="button" value="수정" onclick="location.href='updateTestForm.jsp?num=<%= num %>'">
			<input type="button" value="삭제" onclick="location.href='deleteTestForm.jsp?num=<%= num %>'">
			<input type="button" value="게시판 목록" onclick="location.href='selectTest.jsp'">
		</div>
<%			
		}else{
%>
		<div class="result-display">
			<div class="align-center">
				글 상세 정보가 없습니다.<br>
				<input type="button" value="게시판 목록" onclick="location.href='selectTest.jsp'">				
			</div>
		</div>
<%
		}
	}catch(Exception e){
%>
		<%-- 에러가 났을 때 보여주기 위해서 UI 처리 --%>
		<div class="result-display">
			<div class="align-center">
				오류 발생! 글 상세 정보 호출 실패!<br>
				<input type="button" value="게시판 목록" onclick="location.href='selectTest.jsp'">	
			</div>
		</div>
<%
		e.printStackTrace();
	}finally{
		if(rs!=null) try{rs.close();} catch(SQLException e){}
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</div>
</body>
</html>

 

 

 


 

 

 

상세 페이지에서 수정 버튼 누를 때 수정하는 form 생성

(비밀번호 인증 없이)

 

updateTestForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %> <%-- 날짜 수정은 안할거라 date는 import x --%>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글수정</title>
<link rel="stylesheet" href="style.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{
		//JDBC 수행 1단계 : 드라이버 로드
		Class.forName(driverName);
		
		//JDBC 수행 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		//SQL문 작성
		sql = "SELECT * FROM tboard WHERE num=?";
				
		//JDBC 수행 3단계 : PreparedStatement 객체 생성
		pstmt = conn.prepareStatement(sql);
		
		//?에 데이터 바인딩
		pstmt.setInt(1, num);
		
		//JDBC 수행 4단계 : SQL문을 테이블에 반영하고 결과행들을 ResultSet에 담음
		rs = pstmt.executeQuery();
		if(rs.next()){
			String name = rs.getString("name");
			String title = rs.getString("title");
			String content = rs.getString("content");
%>
	<form id="myForm" action="updateTest.jsp" method="post">
		<%-- 한 행을 통째로 update하는데 num은 필수고, 값을 임의로 수정하면 안되니까 숨겨서 보낼거임 --%>
		<input type="hidden" name="num" value="<%= num %>">
		<ul>
			<li>
				<label for="name">이름</label>
				<input type="text" name="name" id="name" value="<%= name %>" size="20" maxlength="10">
			</li>
			<li>
				<label for="title">제목</label>
				<input type="text" name="title" id="title" value="<%= title %>" size="30" maxlength="50">
			</li>
			<li>
				<label for="passwd">비밀번호</label>
				<input type="password" name="passwd" id="passwd" size="20" maxlength="10">
			</li>
			<li>
				<label for="content">내용</label>
				<%-- textarea는 >< 사이에 공백/ 줄바꿈이 다 반영되기 때문에 주의해야함 --%>
				<textarea rows="5" cols="40" name="content" id="content"><%= content %></textarea>
			</li>
		</ul>
		<div class="align-center">
			<input type="submit" value="수정">
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</form>

<%			
		}else{
			
%>
	<div class="result-display">
		<div class="align-center">
			수정할 글 정보 호출 실패!<br>
			<input type="button" value="게시판 목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
				
<%		

		}
	}catch(Exception e){
		
%>		
	<div class="result-display">
		<div class="align-center">
			오류 발생! 수정할 글 정보 호출 실패!<br>
			<input type="button" value="게시판 목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
		e.printStackTrace();
	}finally{
		//자원정리
		if(rs!=null) try{rs.close();} catch(SQLException e){}
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}

%>
</div>
</body>
</html>

 

form method를 기재안하면 기본적으로 다 get 방식 (post방식은 method="post")

한 행을 통째로 update하려고 하는데 num은 필수고, 값은 임의로 수정하면 안되니까 숨겨서 보냄

type="hidden"

 

 


 

 

 

수정(업데이트) 실행

ResultSet(출력) 은 없고, pstmt로 업데이트

 

 

updateTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글수정</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<%-- 홈에서 post 방식으로 전송했기 때문에 꼭 인코딩 처리 해야함 --%>
<%
	//전송된 데이터 인코딩 처리
	request.setCharacterEncoding("utf-8");
	//전송된 데이터 반환
	int num = Integer.parseInt(request.getParameter("num"));
	String name = request.getParameter("name");
	String title = request.getParameter("title");
	String passwd = request.getParameter("passwd");
	String content = request.getParameter("content");
	
	//DB 연동
	Connection conn = null;
	PreparedStatement pstmt = null;
	String sql = null;

	try{
		//JDBC 1단계 : 드라이버 로드
		Class.forName(driverName);
		
		//JDBC 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl,dbId,dbPass);
		
		//SQL문 작성
		sql = "UPDATE tboard SET name=?,title=?,passwd=?,content=? WHERE num=?";
		
		//JDBC 3단계 : PreparedStatement 객체 생성
		pstmt = conn.prepareStatement(sql);
		
		//?에 데이터 바인딩
		pstmt.setString(1, name);
		pstmt.setString(2, title);
		pstmt.setString(3, passwd);
		pstmt.setString(4, content);
		pstmt.setInt(5, num);
		
		//JDBC 4단계 : SQL문 실행
		pstmt.executeUpdate();
%>
		<div class="result-display">
			<div class="align-center">
				글 수정 완료!<br>
				<input type="button" value="글상세" onclick="location.href='detailTest.jsp?num=<%= num %>'">
			</div>
		</div>
<%
	}catch(Exception e){
%>
	<div class="result-display">
		<div class="align-center">
			오류 발생! 글수정 실패!<br>
			<input type="button" value="글수정 폼" onclick="location.href='updateTestForm.jsp?num=<%= num %>'">
		</div>
	</div>
<%
		e.printStackTrace();
	}finally{
		//자원 정리
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>

 

 

 


 

 

 

삭제할지 말지 결정하는 form

post 방식으로 전송

 

 

deleteTestForm.jsp

<%@ 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="style.css" type="text/css">
</head>
<body>
<%
	int num = Integer.parseInt(request.getParameter("num"));
%>
<div class="page-main">
	<h2>글삭제</h2>
	<p class="align-center">
		<span>정말 삭제하시겠습니까?</span>
	</p>
	<form action="deleteTest.jsp" method="post">
		<input type="hidden" name="num" value="<%= num %>">
		<div class="align-center">
			<input type="submit" value="삭제">
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>
	</form>
</div>
</body>
</html>

 

 

 


 

 

 

삭제 

deleteTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글삭제 처리</title>
<link rel="stylesheet" href="style.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{
		//JDBC 수행 1단계 : 드라이버 로드
		Class.forName(driverName);
		//JDBC 수행 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		//SQL문 작성
		sql = "DELETE FROM tboard WHERE num=?";
		
		//JDBC 수행 3단계 : PreparedStatement 객체 생성
		pstmt = conn.prepareStatement(sql);
		//?에 데이터 바인딩
		pstmt.setInt(1, num);
		
		//JDBC 수행 4단계 : SQL문 실행
		pstmt.executeUpdate();
%>
	<div class="result-display">
		<div class="align-center">
			글삭제 완료!<br>
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
	}catch(Exception e){
%>		
	<div class="result-display">
		<div class="align-center">
			오류 발생! 글삭제 실패!<br>
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
		e.printStackTrace();
	}finally{
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>

 

 

 


 

 

 

[실습]

DB연동해서 게시판 만든 것처럼 상품 페이지 만들기

 

 

github commit 했음

ch05-ServletMain  src/main/webapp/ch11-jdbc2

 

12개 파일

-style.css/ dbInfo.jsfp >> ch10 복붙

-table.sql 로 오라클 table/sequence 생성

-insertTestForm/ insertTest // 

  script.js

  selectTest

  detailTest

  updateTestForm/ updateTest

  deleteTestForm/ deleteTest 순으로 작성

 

 

 

table.sql

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;

 

 

 

insertTestForm.jsp

<%@ 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="style.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="page-main">
	<h2>상품 등록</h2>
	<form id="myForm" action="insertTest.jsp" method="post">
		<ul>
			<li>
				<label for="name">상품명</label>
				<input type="text" name="name" id="name" size="20" maxlength="10">
			</li>
			<li>
				<label for="price">가격</label>
				<input type="number" name="price" id="price" min="1" max="99999999">
			</li>
			<li>
				<label for="stock">재고</label>
				<input type="number" name="stock" id="stock" min="1" max="99999999">
			</li>
			<li>
				<label for="origin">원산지</label>
				<input type="text" name="origin" id="origin" size="20" maxlength="10">
			</li>
		</ul>
		<div class="align-center">
			<input type="submit" value="전송">
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</form>
</div>
</body>
</html>

 

 

 

 

insertTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 등록 처리</title>
<link rel="stylesheet" href="style.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{
		//JDBC 수행 1단계 : 드라이버 로드
		Class.forName(driverName);
		//JDBC 수행 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl,dbId,dbPass);
		//SQL문 작성
		sql = "INSERT INTO product (num,name,price,stock,origin,reg_date) VALUES (product_seq.nextval,?,?,?,?,SYSDATE)";
		//JDBC 수행 3단계 : prepareStatement 객체 생성
		pstmt = conn.prepareStatement(sql);
		//?에 데이터 바인딩
		pstmt.setString(1, name);
		pstmt.setInt(2, price);
		pstmt.setInt(3, stock);
		pstmt.setString(4, origin);
		//JDBC 수행 4단계 : SQL문 실행
		pstmt.executeUpdate();
%>
	<div class="result-display">
		<div class="align-center">
			상품 등록 성공!<br>
			<input type="button" value="목록보기" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
	}catch(Exception e){
%>		
	<div class="result-display">
		<div class="align-center">
			오류 발생! 상품 등록 실패!<br>
			<input type="button" value="상품 등록폼" onclick="location.href='insertTestForm.jsp'">
		</div>
	</div>
<%		
		e.printStackTrace();
	}finally{
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>

 

 

 

 

script.js

window.onload=function(){
	let myForm = document.getElementById('myForm');
	//이벤트 연결
	myForm.onsubmit=function(){
		let items = documen.querySelectorAll('input[type="text"],input[type="number"],textarea');
		for(let i=0; i<items.length; i++){
			if(items[i].value.trim()==''){
				let label = document.querySelector('label[for="'+ items[i].id +'"]');
				alert(label.textContent + '항목은 필수입력');
				items[i].value = '';
				items[i].focus();
				return false;
			}
		}
	};
};

 

 

 

 

 

selectTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %> <%-- 목록처리 하는 곳이라 resultSet이 필요함 (루프) --%>
<%@ page import="java.sql.Date" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 목록 보기</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="page-main">
	<h2>상품 목록 보기</h2>
	<div class="align-right">
		<input type="button" value="글쓰기" onclick="location.href='insertTestForm.jsp'">
	</div>
	
<%
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = null;
	try{
		Class.forName(driverName);
		conn = DriverManager.getConnection(jdbcUrl,dbId,dbPass);
		
		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>
			<th>원산지</th>
			<th>등록일</th>
		</tr>

<%
		while(rs.next()){
			int num = rs.getInt("num");
			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");
%>
		<tr>
			<td><%= num %></td>
			<td><a href="detailTest.jsp?num=<%= num %>"><%= name %></a></td>
			<td class="align-right"><%= String.format("%,d원", price) %></td>
			<td class="align-right"><%= String.format("%,d개",stock) %></td>
			<td><%= origin %></td>
			<td><%= reg_date %></td>	
		</tr>	
<%			
		}
%>		
	</table>
<%		
	}catch(Exception e){
%>
	<div class="result-display">
		<span>오류 발생</span>
	</div>
<%
		e.printStackTrace();
	}finally{
		if(rs!=null) try{rs.close();} catch(SQLException e){}
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>	
</div>
</body>
</html>

 

 

 

 

detailTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Date" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 상세 정보 보기</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<%
	int num = Integer.parseInt(request.getParameter("num"));

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = null;

	try{
		Class.forName(driverName);
		conn=DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		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");
			String reg_date = rs.getString("reg_date");
%>
	<div class="page-main">
		<h2>상품 정보</h2>
			<ul>
				<li>글번호 : <%= num %></li>
				<li>상품명 : <%= name %></li>
				<li>가격 : <%= String.format("%,d원",price) %></li>
				<li>재고 : <%= String.format("%,d개",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="수정" onclick="location.href='updateTestForm.jsp?num=<%= num %>'">
			<input type="button" value="삭제" onclick="location.href='deleteTestForm.jsp?num=<%= num %>'">
			<input type="button" value="상품 목록" onclick="location.href='selectTest.jsp'">
		</div>	
	</div>
<%		
		}else{
%>
		<div class="result-display">
			<div class="align-center">
				상품 정보가 없습니다.<br>
				<input type="button" value="상품 목록" onclick="location.href='selectTest.jsp'">
			</div>
		</div>
<%			
		}
	}catch(Exception e){
%>
		<div class="result-display">
			<div class="align-center">
				오류 발생! 상품 정보 호출 실패!<br>
				<input type="button" value="상품 목록" onclick="location.href='selectTest.jsp'">
			</div>
		</div>
<%		
		e.printStackTrace();
	}finally{
		if(rs!=null) try{rs.close();} catch(SQLException e){}
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</div>
</body>
</html>

 

 

 

 

updateTestForm

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.SQLException"%>
<%@ page import = "java.sql.DriverManager" %>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 수정</title>
<link rel="stylesheet" href="style.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{
		Class.forName(driverName);
		conn = DriverManager.getConnection(jdbcUrl,dbId,dbPass);
		
		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 id="myForm" action="updateTest.jsp" method="post">
		<input type="hidden" name="num" value="<%= num %>">	
		<ul>
			<li>
				<label for="name">상품명</label>
				<input type="text" name="name" id="name" size="20" maxlength="10">
			</li>
			<li>
				<label for="price">가격</label>
				<input type="number" name="price" id="price" min="1" max="99999999">
			</li>
			<li>
				<label for="stock">재고</label>
				<input type="number" name="stock" id="stock" min="1" max="99999999">
			</li>
			<li>
				<label for="origin">원산지</label>
				<input type="text" name="origin" id="origin" size="20" maxlength="10">
			</li>
		</ul>
		<div class="align-center">
			<input type="submit" value="수정">
			<input type="button" value="목록" onclick = "location.href='selectTest.jsp'">
		</div>
	</form>
<%			
		}else{
%>
	<div class="result-display">
		<div class="align-center">
			오류 발생! 상품 정보 수정 폼 호출 실패!<br>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>

<%			
		}
	}catch(Exception e){
%>
	<div class="result-display">
		<div class="align-center">
			오류 발생! 상품 정보 수정 폼 호출 실패!<br>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
		e.printStackTrace();
	}finally{
		//자원정리
		if(rs!=null) try{rs.close();} catch(SQLException e){}
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</div>
</body>
</html>

detailTest.jsp 에서 수정하기 버튼을 누르면 여기로 들어오게 되는데 num 값에 해당하는 컬럼들의 수정목록을 다

입력하게 되고 이 목록을 또 updateTest.jsp로 보냄 

 

 

 

 

updateTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 수정</title>
<link rel="stylesheet" href="style.css" type="text/css">
</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{
		Class.forName(driverName);
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		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">
			상품 수정 완료!<br>
			<input type="button" value="상품상세" onclick="location.href='detailTest.jsp?num=<%= num %>'">
		</div>
	</div>
<%		
	}catch(Exception e){
%>
	<div class="result-display">
		<div class="align-center">
			오류 발생! 상품 수정 실패!<br>
			<input type="button" value="상품수정 폼" onclick="location.href='updateTestForm.jsp?num=<%= num %>'">
		</div>
	</div>
<%		
		e.printStackTrace();
	}finally{
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>

form에서 입력한 정보들을 읽어와서 update 구문 실행

 

 

 

deleteTestForm

<%@ 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="style.css" type="text/css">
</head>
<body>
<%
	int num = Integer.parseInt(request.getParameter("num"));
%>
<div class="page-main">
	<h2>상품 삭제</h2>
	<p class="align-center">
		<span>정말 삭제하시겠습니까?</span>
	</p>
	<form action="deleteTest.jsp" method="post">
		<input type="hidden" name="num" value="<%= num %>">
		<div class="align-center">
			<input type="submit" value="삭제">
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>
	</form>
</div>
</body>
</html>

 

 

 

 

deleteTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ include file="dbInfo.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 삭제 처리</title>
<link rel="stylesheet" href="style.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{
		Class.forName(driverName);
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		sql = "DELETE FROM product WHERE num=?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, num);
		
		pstmt.executeUpdate();
%>
	<div class="result-display">
		<div class="align-center">
			상품 삭제 완료!<br>
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
<%		
	}catch(Exception e){
%>
	<div class="result-main">
		<div class="align-center">
			오류 발생! 상품 삭제 실패!<br>
			<input type="button" value="목록 보기" onclick="location.href='selectTest.jsp'">
		</div>	
	</div>
<%		
		e.printStackTrace();
	}finally{
		if(pstmt!=null) try{pstmt.close();} catch(SQLException e){}
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>
728x90
반응형