index.jsp
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1>게시판 프로젝트</h1>
<ul>
<li><a href="board">고고고</a></li>
</ul>
</body>
</html>
BoardServlet.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.BoardDao;
public class BoardServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("성공");
req.setCharacterEncoding("euc-kr");
resp.setCharacterEncoding("euc-kr");
String KeyField = req.getParameter("KeyField");
String KeyWord = req.getParameter("KeyWord");
req.setAttribute("boardList", new BoardDao().getBoardList(KeyWord, KeyField));
RequestDispatcher view = req.getRequestDispatcher("List.jsp");
view.forward(req, resp);
}
}
DBConnectionMgr.java
public class DBConnectionMgr {//vector와 AllayList를 차이 vector는 동시접근을 막음.
private Vector connections = new Vector(10);
//POOL 10개 /(Collection)VECTOR를 쓴 이유 : 다 쓰면 자동으로 추가시키도록
private String _driver = "com.mysql.jdbc.Driver",
//_url = "jdbc:mysql://localhost:3306/test",
_user = "root",
_password = "1111";
private boolean _traceOn = false;
private boolean initialized = false;
private int _openConnections = 10;
private static DBConnectionMgr instance = null;
......
BoardDto.jsp
package model;
public class BoardDto {
private int no;
private String subject;
private String name;
private String regdate;
private int cnt;
private String email;
private String homepage;
private String pw;
private String content;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHomepage() {
return homepage;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
BoardDao.java
package model;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.Connection;
import mybean.dbcp.DBConnectionMgr;
public class BoardDao {
private DBConnectionMgr pool;
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public BoardDao() {
try {
pool = DBConnectionMgr.getInstance();
}
catch(Exception err) {
System.out.println("BoardDao() 오류 : " + err);
}
}
//목록을 불러오는 메소드
public List<BoardDto> getBoardList(String KeyWord, String KeyField){
ArrayList<BoardDto> list = new ArrayList<>();
String sql = "";
if( KeyField == null ) {
KeyField = "name";
KeyWord = "";
}
System.out.println("keyword : " + KeyWord);
if(KeyWord.equals("") && KeyField.isEmpty()) {
sql = "select * from board order by no desc";
}else {
sql = "select * from board where "+ KeyField +" like '%" + KeyWord + "%' order by no desc";
}
try {
conn = (Connection)pool.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
BoardDto board = new BoardDto();
board.setNo(rs.getInt("no"));
board.setSubject(rs.getString("subject"));
board.setName(rs.getString("name"));
board.setRegdate(rs.getString("regdate"));
board.setCnt(rs.getInt("cnt"));
list.add(board);
}
}catch(Exception err) {
err.printStackTrace();
}finally {
pool.freeConnection(conn, pstmt, rs);
}
return list;
}
//글 읽는 메소드가 필요 Read.jsp
public BoardDto getBoard(int no, boolean hasRead) {
BoardDto board = new BoardDto();
String sql="";
try {
conn = (Connection) pool.getConnection();
if(hasRead == true) {//읽었으니깐 카운트 올려주기한 update
sql = "update board set cnt=cnt+1 where no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
pstmt.executeUpdate();
//sql문의 1개의 바인딩 변수에 값을 채운 후 executeUpdate()메소드를 호출해
//update문을 실행시켜 데이터 베이스에 정보를 수정함.
}
//카운트를 올려주고 나서 이제 글을 가져와야함.
sql = "select * from board where no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
//pstmt.executeQuery(); 얘는 select문으로 값을 가져오게끔 했으므로 결과값을 담아 넣을 변수가 필요함.
rs = pstmt.executeQuery();
while(rs.next()) {
board.setNo(rs.getInt("no"));
board.setSubject(rs.getString("subject"));
board.setName(rs.getString("name"));
board.setRegdate(rs.getString("regdate"));
board.setCnt(rs.getInt("cnt"));
board.setHomepage(rs.getString("homepage"));
board.setEmail(rs.getString("email"));
board.setContent(rs.getString("content"));
board.setPw(rs.getString("pw"));
}
}catch(Exception err) {
System.out.println("getBoard()에러 : " + err);
}finally {
pool.freeConnection(conn, pstmt, rs); }
return board;
}
//글 등록하는 메소드 Post.jsp
public void insertBoard(BoardDto board) {
try {
conn = (Connection) pool.getConnection();
String sql = "insert into board(name, subject, email, "
+ "homepage, pw, content, regdate, cnt) "
+ "value(?, ?, ?, ?, ?, ?, now(), 0)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getName());
pstmt.setString(2, board.getSubject());
pstmt.setString(3, board.getEmail());
pstmt.setString(4, board.getHomepage());
pstmt.setString(5, board.getPw());
pstmt.setString(6, board.getContent());
//pstmt.setString(7, board.getRegdate());
//regdate와 cnt는 그냥 알아서 들어가라고 하고 위는 받아와서 ?에 넣으라는 소리였음! 아항~!
pstmt.executeUpdate();
}catch(Exception err) {
System.out.println("insertBoard()에러 : " + err);
}finally {
pool.freeConnection(conn, pstmt);
}
} //db에 집어넣는 거니깐 return 값 없어도 됨.
//글 수정하는 메소드 updateProc.jsp
public void updateBoard(BoardDto board) {
try {
conn = (Connection) pool.getConnection();
String sql = "update board set name=?, email=?, "
+ "subject=?, content=?, pw=? where no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getName());
pstmt.setString(2, board.getEmail());
pstmt.setString(3, board.getSubject());
pstmt.setString(4, board.getContent());
pstmt.setString(5, board.getPw());
pstmt.setInt(6, board.getNo());
pstmt.executeUpdate();
}catch(Exception err) {
System.out.println("UpdateBoard()에러 : " + err );
}finally {
pool.freeConnection(conn, pstmt);
}
}
//글 삭제하는 메소드 delete.jsp
public void deleteBoard(int no) {
try {
conn = (Connection) pool.getConnection();
String sql = "delete from board where no=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
pstmt.executeUpdate();
}catch(Exception err) {
System.out.println("deleteBoard()에러 : " + err);
}finally {
pool.freeConnection(conn, pstmt);
}
//update했으면 끝이지 뭐 리턴값 없어
}
}
List.jsp
<%@page import="model.BoardDto"%>
<%@page import="java.util.ArrayList"%>
<%@ page contentType="text/html;charset=euc-kr" %>
<HTML>
<head>
<link rel="stylesheet" href="bootstrap337/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="bootstrap337/css/bootstrap.min.css">
<style type="text/css">
th{
text-align:center;
background-color:lightgrey;
color:#999990;
}
.table>tbody>tr>td{
text-align:center;
}
</style>
<script>
function Read(no){
document.Read.no.value = no;
document.Read.submit();
}
function check(){
if(document.Search.KeyWord.value == "" ){
alert("검색어를 입력하세요");
document.Search.KeyWord.focus();
return;
}
document.Search.submit();
}
</script>
<title>메인 게시판 화면임</title>
</head>
<body>
<div>
<table>
<tr>
<td align=left>Total : Articles( <font color=red> 1 / 10 Pages </font>)
</td>
</tr>
</table>
</div>
<div class="col-md-10">
<table class="table table-striped">
<tr>
<th>글 번호</th>
<th>글 제목</th>
<th>작성자</th>
<th>작성날짜</th>
<th>조회수</th>
<tr>
<c:forEach items="${boardList}" var="list">
<%--↑ 전체글이 다 뿌려짐 --%>
<tr>
<td>${list.no}</td>
<td><a href="javascript:Read(${list.no})">${list.subject}</a></td>
<td>${list.name}</td>
<td>${list.regdate}</td>
<td>${list.cnt}</td>
</tr>
</c:forEach>
<tr>
<td align="left">Go to Page</td>
<td align="right"><a href="Post.jsp">[글쓰기]</a>
<a href="board">[처음으로]</a>
</td>
</tr>
</table>
</div>
<BR>
<%--검색기능 --%>
<form action="board" name="Search" method="post">
<table border=0 width=527 align=center cellpadding=4 cellspacing=0>
<tr>
<td align=center valign=bottom>
<select name="KeyField" size="1">
<option value="name"> 이름
<option value="subject"> 제목
<option value="content"> 내용
</select>
<input type="text" size="16" name="KeyWord">
<input type="button" value="찾기" onClick="check()">
<input type="hidden" name="page" value= "0">
</td>
</tr>
</table>
</form>
<form name="Read" action="ReadServlet" method="post">
<input type="hidden" name="no">
<input type="hidden" name="command" value="Read">
</form>
</body>
</HTML>
Post.jsp
<%@ page contentType="text/html; charset=EUC-KR" %>
<html>
<head><title>JSPBoard</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script>
function btn(){
if(document.post.subject.value == ""){
alert("내용을 적어주세요!");
}else if( document.post.pw.value == ""){
alert("비밀번호를 적어주세요!");
}else{
document.post.submit();
}
}
</script>
</head>
<body>
<br><br>
<table width=80% cellspacing=0 cellpadding=3>
<tr>
<td bgcolor=84F399 height=25 align=center>글쓰기</td>
</tr>
</table>
<br>
<table width=80% cellspacing=0 cellpadding=3 align=center>
<form name="post" action="PostServlet" method="post" >
<tr>
<td align=center>
<table border=0 width=100% align=center>
<tr>
<td width=10%>성 명</td>
<td width=90%><input type=text name=name size=10 maxlength=8></td>
</tr>
<tr>
<td width=10%>E-Mail</td>
<td width=90%><input type=text name=email size=30 maxlength=30></td>
</tr>
<tr>
<td width=10%>홈페이지</td>
<td width=90%><input type=text name=homepage size=40 maxlength=30></td>
</tr>
<tr>
<td width=10%>제 목</td>
<td width=90%><input type=text name=subject size=50 maxlength=30></td>
</tr>
<tr>
<td width=10%>내 용</td>
<td width=90%><textarea name=content rows=10 cols=50></textarea></td>
</tr>
<tr>
<td width=10%>비밀 번호</td>
<td width=90% ><input type=password name=pw size=15 maxlength=15></td>
</tr>
<tr>
<td colspan=2><hr size=1></td>
</tr>
<tr>
<td><input type="button" value="등록" onclick="btn()">
<input type=reset value="다시쓰기">
</td>
</tr>
</table>
</td>
</tr>
</form>
</table>
</body>
</html>
Read.jsp
<%@page import="model.BoardDto"%>
<%@page import="model.BoardDao"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<html>
<head><title>JSPBoard</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script>
function List(){
document.List.submit();
}
function Update(no){
document.Update.no.value = no;
document.Update.submit();
}
function Delete(no,pw){
document.Delete.no.value = no;
document.Delete.pw.value = pw;
document.Delete.submit();
}
</script>
</head>
<body>
<% request.setCharacterEncoding("euc-kr"); %>
<br><br>
<table align=center width=70% border=0 cellspacing=3 cellpadding=0>
<tr>
<td bgcolor=9CA2EE height=25 align=center class=m>글읽기</td>
</tr>
<tr>
<td colspan=2>
<table border=0 cellpadding=3 cellspacing=0 width=100%>
<tr>
<td align=center bgcolor=#dddddd width=10%> 이 름 </td>
<td bgcolor=#ffffe8>${Read.name}</td>
<td align=center bgcolor=#dddddd width=10%> 등록날짜 </td>
<td bgcolor=#ffffe8>${Read.regdate}</td>
</tr>
<tr>
<td align=center bgcolor=#dddddd width=10%> 메 일 </td>
<td bgcolor=#ffffe8 >${Read.email}</td>
<td align=center bgcolor=#dddddd width=10%> 홈페이지 </td>
<td bgcolor=#ffffe8 ><a href="http://" target="_new">${Read.homepage}</a></td>
</tr>
<tr>
<td align=center bgcolor=#dddddd> 제 목</td>
<td bgcolor=#ffffe8 colspan=3>${Read.subject}</td>
</tr>
<tr>
<td colspan=4>${Read.content}</td>
</tr>
<tr>
<td colspan=4 align=right>
${Read.name} 로 부터 글을 남기셨습니다. | 조회수 : ${Read.cnt}
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align=center colspan=2>
<hr size=1>
[ <a href="javascript:List()">목 록</a> |
<a href="javascript:Update(${Read.no})">수 정</a> |
<a href="javascript:Delete(${Read.no},${Read.pw})">삭 제</a> ]<br>
</td>
</tr>
</table>
<form name="List" action="board" method="post"></form>
<form name="Update" action="ReadServlet" method="post" >
<input type="hidden" name="command" value="Update">
<input type="hidden" name="no">
</form>
<form name="Delete" action ="Delete.jsp" method="post">
<input type="hidden" name="no">
<input type="hidden" name="pw">
</form>
</body>
</html>
Update.jsp
<%@ page contentType="text/html; charset=EUC-KR"%>
<html>
<head> <title>JSPBoard</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script>
function check(){
if(document.UpdateProc.pw.value == ""){
alert("비번을 입력해야 함.");
document.UpdateProc.focus();
return false;
}
document.UpdateProc.submit();
}
</script>
</head>
<body>
<br><br>
<table width=460 cellspacing=0 cellpadding=3>
<tr>
<td bgcolor=#FF9018 height=21 align=center class=m>수정하기</td>
</tr>
</table>
<form name="UpdateProc" action="UpdateServlet" method="post">
<input type="hidden" name="no" value="${Update.no}">
<table width=70% cellspacing=0 cellpadding=7>
<tr>
<td align=center>
<table border=0>
<tr>
<td width=20%>성 명</td>
<td width=80%>
<input type=text name=name size=30 maxlength=20 value="${Update.name}">
</td>
</tr>
<tr>
<td width=20%>E-Mail</td>
<td width=80%>
<input type=text name=email size=30 maxlength=30 value="${Update.email}">
</td>
</tr>
<tr>
<td width=20%>제 목</td>
<td width=80%>
<input type=text name=subject size=50 maxlength=50 value="${Update.subject}">
</td>
<tr>
<td width=20%>내 용</td>
<td width=80%>
<textarea name=content rows=10 cols=50>${Update.content}</textarea>
</td>
</tr>
<tr>
<td width=20%>비밀 번호</td>
<td width=80%><input type=password name=pw size=15 maxlength=15>
수정시에는 비밀번호가 필요합니다.</td>
</tr>
<tr>
<td colspan=2 height=5><hr size=1></td>
</tr>
<tr>
<td colspan=2>
<input type=Button value="수정완료" onClick="check()">
<input type=reset value="다시수정">
<input type=button value="뒤로" onClick="history.back()">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
PostServlet.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.BoardDao;
import model.BoardDto;
public class PostServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("성공");
req.setCharacterEncoding("euc-kr");
resp.setCharacterEncoding("euc-kr");
BoardDto board = new BoardDto(); //값을 받아와서 DTO에 저장
board.setName(req.getParameter("name"));
board.setSubject(req.getParameter("subject"));
board.setEmail(req.getParameter("email"));
board.setHomepage(req.getParameter("homepage"));
board.setPw(req.getParameter("pw"));
board.setContent(req.getParameter("content"));
new BoardDao().insertBoard(board);
RequestDispatcher view = req.getRequestDispatcher("board");
view.forward(req, resp);
}
}
ReadServlet.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.BoardDao;
import model.BoardDto;
public class ReadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("성공");
String command = req.getParameter("command");
String url = "";
int no = Integer.parseInt(req.getParameter("no"));
String pw = req.getParameter("pw");
if(command.equals("Read")) {
req.setAttribute("Read", new BoardDao().getBoard(no, true));
url = "Read.jsp";
}else if(command.equals("Update")) {
req.setAttribute("Update", new BoardDao().getBoard(no, true));
url = "Update.jsp";
}
else if(command.equals("Delete")) {
BoardDto board = new BoardDao().getBoard(no, true);
if(pw != null) {
if(pw.equals(board.getPw())) {
new BoardDao().deleteBoard(no);
url = "board";
} else {
url = "Delete.jsp";
}
}
}
RequestDispatcher view = req.getRequestDispatcher(url);
view.forward(req, resp);
}
}
UpdateServlet.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.BoardDao;
import model.BoardDto;
public class UpdateServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("성공인감");
req.setCharacterEncoding("euc-kr");
resp.setCharacterEncoding("euc-kr");
int no = Integer.parseInt(req.getParameter("no"));
BoardDto board = new BoardDao().getBoard(no, true);
board.setName(req.getParameter("name"));
board.setEmail(req.getParameter("email"));
board.setSubject(req.getParameter("subject"));
board.setContent(req.getParameter("content"));
board.setNo(Integer.parseInt(req.getParameter("no")));
String url="";
if(req.getParameter("pw").equals(board.getPw())){
//여기까지 dto에 저장을 한거임. 이제 dao 메소드에 보내줌.
new BoardDao().updateBoard(board);
url = "board";
} else {
req.setAttribute("Read", board);
url = "Read.jsp";
}
RequestDispatcher view = req.getRequestDispatcher(url);
//자꾸 list.jsp로 보낼려고 하는데 이것도 요청이고 글 목록 그래로 가져와야 하니깐 board(servlet)으로 보내야지
System.out.println("url : " + url);
view.forward(req, resp);
}
}