Please Enable JavaScript!
Mohon Aktifkan Javascript![ Enable JavaScript ]

[JDBC]방명록 만들기

2010. 6. 4. 12:37programming/JDBC

728x90
** 소스 목록 **
1. guestbook_list.jsp
2. guestbook_form.jsp
3. guestbook_edit_form.jsp
4. guestbook_control.jsp
5. GuestBook.java
6. GuestBean.java
7. guestbook_error.jsp

테이블 생성
ucreate table guestbook(
gb_id int not null primary key auto_increment,
gb_name varchar(15) not null,
gb_email varchar(50) null,
gb_passwd varchar(6) not null,
gb_tel varchar(14) null,
gb_date datetime not null,
gb_contents varchar(500) null
);
===================================
>>>>>>>> 1. guestbook_list.jsp
===================================

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" errorPage="guestbook_error.jsp" import="java.util.*, guestbook.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language=JavaScript>
function check(gb_id) {
pwd = prompt('수정/삭제 하려면 비밀번호를 넣으세요');
document.location.href="guestbook_control.jsp?action=edit&gb_id="+gb_id+"&upasswd="+pwd;
}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>방명록:목록화면</title>
</head>

<%
GuestBean gb = new GuestBean();

//ArrayList<GuestBook> datas = gb.getDBList();
ArrayList datas = gb.getDBList();
%>
<body>
<center>
<H2>방명록:목록화면 </H2>
<HR>
<form>
<a href="guestbook_form.jsp">방명록 쓰기</a><P>

<table cellpadding=5 cellspacing=0 border="1">
<tr  bgcolor="#99CCFF" ><td>번호</td><td>작성자</td><td>전화번호</td><td>작성일</td><td>내용</td></tr>
<%
// ArrayList 객체를 통해 DB에서 가져온 목록을 출력함.
//for(GuestBook guestbook : datas) {
for(int i=0; i<datas.size(); i++) {
GuestBook guestbook = (GuestBook)(datas.get(i));
%>
 <tr>
  <td><%=guestbook.getGb_id() %></td>
<td><%=guestbook.getGb_name() %></td>
<td><%=guestbook.getGb_tel() %></td>
<td><%=guestbook.getGb_date() %></td>
<td><a href=javascript:check('<%=guestbook.getGb_id() %>')><%=guestbook.getGb_contents() %></a></td>
 </tr>
<%
}
%>
</table>
</form>
<HR>
</center>
</body>
</html>
===================================
>>>>>>>> 2. guestbook_form.jsp
===================================

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" errorPage="guestbook_error.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>방명록:작성화면</title>
</head>
<body>
<center>
<H2>방명록:작성화면 </H2>
<HR>
[<a href=guestbook_control.jsp?action=list>게시물목록으로</a>]
<form name=form1 method=post action=guestbook_control.jsp>
<input type=hidden name="action" value="insert">
<table cellpadding=5 cellspacing=0 border="1">
  <tr>
    <td bgcolor="#99CCFF">작 성 자</td>
    <td><input type="text" name="gb_name" size="20"></td>
  </tr>
  <tr>
    <td bgcolor="#99CCFF">email</td>
    <td><input type="text" name="gb_email" size="20"></td>
  </tr>
    <tr>
    <td bgcolor="#99CCFF">전화번호</td>
    <td><input type="text" name="gb_tel" size="20"></td>
  </tr>
  <tr>
    <td bgcolor="#99CCFF">비밀번호</td>
    <td><input type="password" name="gb_passwd" size="20"></td>
  </tr>
  <tr>
    <td colspan="2"><textarea rows="5" name="gb_contents" cols="40"></textarea></td>
  </tr>
  <tr>
    <td colspan=2 align=center><input type=submit value="저장"><input type=reset value="취소"></td>
</tr>
</table>
</form>

</center>
</body>
</html>

===================================
>>>>>>>> 3. guestbook_edit_form.jsp
===================================
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" errorPage="guestbook_error.jsp" import="guestbook.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language=JavaScript>
// 삭제 확인을 위한 자바스크립트
function delcheck() {
// 메시지 창을 통해 YES/NO 확인
result = confirm("정말로 삭제하시겠습니까 ?");
if(result == true){
document.form1.action.value="delete";
document.form1.submit();
}
else
return;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>방명록:수정화면</title>
</head>

<%
GuestBook guestbook = (GuestBook)request.getAttribute("gbook"); 
%>

<body>
<center>
<H2>방명록:수정화면 </H2>
<HR>
[<a href=guestbook_control.jsp?action=list>게시물목록으로</a>]
<form name=form1 method=post action=guestbook_control.jsp>
<input type=hidden name="gb_id" value="<%=guestbook.getGb_id()%>">
<input type=hidden name="action" value="update">

<table cellpadding=5 cellspacing=0 border="1">
  <tr>
    <td bgcolor="#99CCFF">작 성 자</td>
    <td><input type="text" name="gb_name" size="20" value="<%=guestbook.getGb_name() %>"></td>
  </tr>
  <tr>
    <td bgcolor="#99CCFF">email</td>
    <td><input type="text" name="gb_email" size="20" value="<%=guestbook.getGb_email() %>"></td>
  </tr>
    <tr>
    <td bgcolor="#99CCFF">전화번호</td>
    <td><input type="text" name="gb_tel" size="20" value="<%=guestbook.getGb_tel() %>"></td>
  </tr>
  <tr>
    <td bgcolor="#99CCFF">비밀번호</td>
    <td><input type="password" name="gb_passwd" size="20" value="<%=guestbook.getGb_passwd()%>"></td>
  </tr>
  <tr>
    <td colspan="2"><textarea rows="5" name="gb_contents" cols="40"><%=guestbook.getGb_contents() %></textarea></td>
  </tr>
  <tr>
    <td colspan=2 align=center>
    <input type=submit value="저장"><input type=reset value="취소"><input type="button" value="삭제" onClick="delcheck()"></td>
</tr>
</table>
</form>

</center>
</body>
</html>

===================================
>>>>>>>> 4. guestbook_control.jsp
===================================
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"  errorPage="guestbook_error.jsp" import = "guestbook.*" %>
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<% request.setCharacterEncoding("euc-kr"); %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="gb" class="guestbook.GuestBean"/>
<jsp:useBean id="guestbook" class="guestbook.GuestBook"/>
<jsp:setProperty name="guestbook" property="*"/>

<% 
// 사용자 요청을 구분하기 위한 파라미터를 저장할 변수
String action = request.getParameter("action");
// 게시물 목록 요청인 경우
if(action.equals("list")) {
response.sendRedirect("guestbook_list.jsp");
}
// 게시물 등록 요청인 경우
else if(action.equals("insert")) {
if(gb.insertDB(guestbook)) {
response.sendRedirect("guestbook_list.jsp");
}
else
throw new Exception("DB 입력오류");
}
// 게시물 수정화면 요청인 경우
else if(action.equals("edit")) {
GuestBook gbook = gb.getDB(guestbook.getGb_id());
if(!gbook.getGb_passwd().equals(request.getParameter("upasswd"))) {
out.println("<script>alert('비밀번호가 틀렸습니다.!!'); history.go(-1);</script>");
}
else {
request.setAttribute("gbook",gbook);
   pageContext.forward("guestbook_edit_form.jsp");
}
}
// 게시물 수정 처리인 경우
else if(action.equals("update")) {
if(gb.updateDB(guestbook)) {
response.sendRedirect("guestbook_list.jsp");
}
else
throw new Exception("DB 갱신오류");
}
// 게시물 삭체 요청인 경우
else if(action.equals("delete")) {
if(gb.deleteDB(guestbook.getGb_id())) {
response.sendRedirect("guestbook_list.jsp");
}
else
throw new Exception("DB 삭제 오류");
}
else {
out.println("<script>alert('action 파라미터를 확인해 주세요!!!')</script>");
}
%>

</body>
</html>


===================================
>>>>>>>> 5. GuestBook.java
===================================

package guestbook;
import java.util.*;
public class GuestBook {
//멤버변수
private int gb_id;
private String gb_name;
private String gb_email;
private String gb_tel;
private Date gb_date;
private String gb_passwd;
private String gb_contents;
public String getGb_contents() {
return gb_contents;
}
public void setGb_contents(String gb_contents) {
this.gb_contents = gb_contents;
}
public Date getGb_date() {
return gb_date;
}
public void setGb_date(Date gb_date) {
this.gb_date = gb_date;
}
public String getGb_email() {
return gb_email;
}
public void setGb_email(String gb_email) {
this.gb_email = gb_email;
}
public int getGb_id() {
return gb_id;
}
public void setGb_id(int gb_id) {
this.gb_id = gb_id;
}
public String getGb_name() {
return gb_name;
}
public void setGb_name(String gb_name) {
this.gb_name = gb_name;
}
public String getGb_tel() {
return gb_tel;
}
public void setGb_tel(String gb_tel) {
this.gb_tel = gb_tel;
}
public String getGb_passwd() {
return gb_passwd;
}
public void setGb_passwd(String gb_passwd) {
this.gb_passwd = gb_passwd;
}

}

===================================
>>>>>>>> 6. GuestBean.java
===================================

package guestbook;
import java.sql.*;
import java.util.*;

public class GuestBean {

// 데이터베이스 연결관련 변수 선언
Connection conn = null;
PreparedStatement pstmt = null;
// MySqql 데이터베이스 연결관련정보를 문자열로 선언
String jdbc_driver = "com.mysql.jdbc.Driver";
String jdbc_url ="jdbc:mysql://localhost:3306/jspdb";
//Oracle 데이터 베이스 연결 관련 정보
//String jdbc_driver = "oracle.jdbc.driver.OracleDriver";
//String jdbc_url = "jdbc:oracle:thin:@127.0.0.1:1521";
// 데이터베이스 연결 메서드
void connect() {
// JDBC 드라이버 로드
try {
Class.forName(jdbc_driver);
// MySQL 데이터베이스 연결정보를 이용해 Connection 인스턴스 확보
conn = DriverManager.getConnection(jdbc_url,"root","ce1111");
// Oracle 데이터베이스 연결정보를 이용해 Connection 인스턴스 확보
//conn = DriverManager.getConnection(jdbc_url,"jspdbuser","jsppasswd");
} catch (Exception e) {
e.printStackTrace();
}
}
// 데이터베이스 연결 종료 메서드
void disconnect() {
if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 데이터 갱신을 위한 메서드
public boolean updateDB(GuestBook guestbook) {
connect();
//Oracle DB 사용 시 gb_date=sysdate 로 작성
String sql ="update guestbook set gb_name=?, gb_email=?, gb_date=sysdate(), gb_tel=?, gb_passwd=?, gb_contents=? where gb_id=?";
try {
pstmt = conn.prepareStatement(sql);
// 인자로 받은 GuestBook 객체를 이용해 사용자가 수정한 값을 가져와 SQL문 완성
pstmt.setString(1,guestbook.getGb_name());
pstmt.setString(2,guestbook.getGb_email());
pstmt.setString(3,guestbook.getGb_tel());
pstmt.setString(4,guestbook.getGb_passwd());
pstmt.setString(5,guestbook.getGb_contents());
pstmt.setInt(6,guestbook.getGb_id());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
disconnect();
}
return true;
}
// 게시물 삭제를 위한 메서드
public boolean deleteDB(int gb_id) {
connect();
String sql ="delete from guestbook where gb_id=?";
try {
pstmt = conn.prepareStatement(sql);
// 인자로 받은 gb_id 프라이머리 키 값을 이용해 삭제
pstmt.setInt(1,gb_id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
disconnect();
}
return true;
}
// 게시물 등록 메서드
public boolean insertDB(GuestBook guestbook) {
connect();
//Oracle DB 일 경우 sysdate 로 작성
String sql ="insert into guestbook(gb_name,gb_email,gb_date,gb_tel,gb_passwd,gb_contents) values(?,?,sysdate(),?,?,?)";
try {
pstmt = conn.prepareStatement(sql);
// 인자로 받은 GuestBook 객체를 통해 사용자 입력값을 받아 SQL 완성후 입력 처리
pstmt.setString(1,guestbook.getGb_name());
pstmt.setString(2,guestbook.getGb_email());
pstmt.setString(3,guestbook.getGb_tel());
pstmt.setString(4,guestbook.getGb_passwd());
pstmt.setString(5,guestbook.getGb_contents());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
disconnect();
}
return true;
}

// 게시물 하나의 모든 정보를 가지고 오는 메서드
public GuestBook getDB(int gb_id) {
connect();
String sql = "select * from guestbook where gb_id=?";
GuestBook guestbook = new GuestBook();
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,gb_id);
ResultSet rs = pstmt.executeQuery();
rs.next();
// 가져와 데이터를 GuestBook 객체로 만들어 리턴함.
guestbook.setGb_id(rs.getInt("gb_id"));
guestbook.setGb_name(rs.getString("gb_name"));
guestbook.setGb_email(rs.getString("gb_email"));
guestbook.setGb_date(rs.getDate("gb_date"));
guestbook.setGb_tel(rs.getString("gb_tel"));
guestbook.setGb_contents(rs.getString("gb_contents"));
guestbook.setGb_passwd(rs.getString("gb_passwd"));
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
disconnect();
}
return guestbook;
}
// 게시물 목록 출력을 위해 전체 게시물을 가지고 오는 메서드
public ArrayList getDBList() {

connect();
// 게시물 목록을 리턴하기 위한 ArrayList 객체 생성, 명시적으로 ArrayList 에 들어갈 데이터 타잎을 선언함.
//ArrayList<GuestBook> datas = new ArrayList<GuestBook>();
ArrayList datas = new ArrayList();
String sql = "select * from guestbook";
try {
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();

// 루프를 돌면 ResultSet 을 이동하면서 모든 데이터 row 를 하나씩 가지고 와서 GuestBook 객체에 넣고 이를 다시 ArrayList 에 넣는 작업을 반복.
while(rs.next()) {
GuestBook guestbook = new GuestBook();
guestbook.setGb_id(rs.getInt("gb_id"));
guestbook.setGb_name(rs.getString("gb_name"));
guestbook.setGb_email(rs.getString("gb_email"));
guestbook.setGb_date(rs.getDate("gb_date"));
guestbook.setGb_tel(rs.getString("gb_tel"));
guestbook.setGb_contents(rs.getString("gb_contents"));
//datas.add(guestbook);
datas.add(guestbook);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
disconnect();
}
// 처리가 끝나 ArrayList 를 리턴함.
return datas;
   }
}


===================================
>>>>>>>> 7. guestbook_error.jsp
===================================

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" isErrorPage="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<body>
<center>
<H2>방명록 에러</H2>
<HR>
<table cellpadding=5 width=400>
<tr width=100% bgcolor="pink"><td>
방명록 처리중 에러가 발생 했습니다.<BR>
관리자에게 문의해 주세요..<BR>
빠른시일내 복구하겠습니다.
<HR>
에러내용 : <%= exception%>
<HR>

</td>
</tr>
</table>
</center>
</body>
</HTML>

728x90

'programming > JDBC' 카테고리의 다른 글

Database 연결 확인 + 이클립스 개발환경 만들기  (0) 2010.06.12
JDBC 드라이브 설치.  (0) 2010.06.12
[JDBC]전화번호부 DB  (0) 2010.05.28
jdbctest.jsp 실습 12주  (0) 2010.05.26
JDBC 데이터 베이스 생성  (0) 2010.05.19