게시판 만들기 – (2) 수정, 삭제
게시판의 수정과 삭제를 구현해 보도록 한다.
어제 수정까지 마무리 짓고 마쳤으니 오늘은 수정과 삭제를 만들어 보도록 하겠다.
수정과 삭제는 글 추가 기능을 만들어 놓은 게시판에 DAO를 이용해 함수를 추가하고 해당 ACTION을 수행하는 jsp 페이지를 만들어주면 된다.
BbsDAO.java
package bbs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class BbsDAO {
private Connection conn;
private ResultSet rs;
public BbsDAO() {
try {
String dbURL = "jdbc:mysql://localhost:3306/BBS?serverTimezone=Asia/Seoul&useSSL=false";
String dbID = "root";
String dbPassword = "root";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL,dbID,dbPassword);
}catch (Exception e) {
e.printStackTrace();
}
}
public String getDate() {
String SQL = "SELECT NOW()";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
return rs.getString(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public int getNext() {
String SQL = "SELECT bbsID FROM BBS ORDER BY bbsID DESC";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
return rs.getInt(1)+1;
}
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public int write(String bbsTitle, String userID, String bbsContent) {
String SQL = "INSERT INTO BBS VALUES (?, ?, ?, ?, ?, ?)";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, getNext());
pstmt.setString(2, bbsTitle);
pstmt.setString(3, userID);
pstmt.setString(4, getDate());
pstmt.setString(5, bbsContent);
pstmt.setInt(6, 1);
return pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public ArrayList<Bbs> getList(int pageNumber){
String SQL = "SELECT * FROM bbs WHERE bbsID < ? AND bbsAvailable =1 ORDER BY bbsID DESC LIMIT 10;";
ArrayList<Bbs> list = new ArrayList<Bbs>();
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, getNext() - (pageNumber -1)*10);
rs = pstmt.executeQuery();
while(rs.next()) {
Bbs bbs = new Bbs();
bbs.setBbsID(rs.getInt(1));
bbs.setBbsTitle(rs.getString(2));
bbs.setUserID(rs.getString(3));
bbs.setBbsDate(rs.getString(4));
bbs.setBbsContent(rs.getString(5));
bbs.setBbsAvailable(rs.getInt(6));
list.add(bbs);
}
}catch(Exception e) {
e.printStackTrace();
}
return list;
}
public boolean nextPage(int pageNumber) {
String SQL = "SELECT * FROM bbs WHERE bbsID < ? AND bbsAvailable =1 ORDER BY bbsID DESC LIMIT 10";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, getNext() - (pageNumber -1)*10);
rs = pstmt.executeQuery();
if(rs.next()) {
return true;
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public Bbs getBbs(int bbsID) {
String SQL = "SELECT * FROM bbs WHERE bbsID = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, bbsID);
rs = pstmt.executeQuery();
if(rs.next()) {
Bbs bbs = new Bbs();
bbs.setBbsID(rs.getInt(1));
bbs.setBbsTitle(rs.getString(2));
bbs.setUserID(rs.getString(3));
bbs.setBbsDate(rs.getString(4));
bbs.setBbsContent(rs.getString(5));
bbs.setBbsAvailable(rs.getInt(6));
return bbs;
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
public int update(int bbsID, String bbsTitle, String bbsContent) {
Bbs bbs = getBbs(bbsID);
String SQL = "UPDATE BBS SET bbsTitle = ?, bbsContent = ? WHERE bbsID = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, bbsTitle);
pstmt.setString(2, bbsContent);
pstmt.setInt(3, bbsID);
return pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public int delete(int bbsID) {
String SQL = "UPDATE BBS SET bbsAvailable = 0 WHERE bbsID = ?";
System.out.println("여기 동작하나"+bbsID);
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, bbsID);
return pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
이 중에 맨 아래에 추가 된 update와 delete를 살펴보자
public int update(int bbsID, String bbsTitle, String bbsContent)
Bbs bbs = getBbs(bbsID);
String SQL = "UPDATE BBS SET bbsTitle = ?, bbsContent = ? WHERE bbsID = ?";
Bbs 클래스를 이용해 수정할 Bbs객체를 불러와 bbs에 저장하고,
SQL쿼리를 이용해 UPDATE 쿼리를 사용한다.
public int delete(int bbsID) {
String SQL = "UPDATE BBS SET bbsAvailable = 0 WHERE bbsID = ?";
Delete 함수는 ID값을 가져와 SQL 쿼리를 이용해 데이터를 찾고 bbsAvailabe 변수를 '0'을 대입하여 게시판에서 볼 수 없게 만든다. 다만 DB에는 데이터가 있다. -- (이 게시판의 삭제 기능)
Update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.PrintWriter"%>
<%@ page import="bbs.Bbs"%>
<%@ page import="bbs.BbsDAO"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width" initial-scale="1">
<link rel="stylesheet" href="css/bootstrap.css">
<title>JSP JSW 게시판 웹사이트</title>
</head>
<body>
<%
String userID = null;
if (session.getAttribute("userID") != null) {
userID = (String) session.getAttribute("userID");
}
if (userID == null) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요.')");
script.println("location.href='login.jsp'");
script.println("</script>");
}
int bbsID = 0;
if (request.getParameter("bbsID") != null) {
bbsID = Integer.parseInt(request.getParameter("bbsID"));
}
if (bbsID == 0) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요.')");
script.println("location.href='bbs.jsp'");
script.println("</script>");
}
Bbs bbs = new BbsDAO().getBbs(bbsID);
if (!userID.equals(bbs.getUserID())) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('권한이 없습니다.')");
script.println("location.href='login.jsp'");
script.println("</script>");
}
%>
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
aria-expanded="false">
<span class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="main.jsp">JSP 게시판 메인</a>
</div>
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<ui class="nav navbar-nav">
<li><a href="main.jsp">메인</a></li>
<li class="active"><a href="bbs.jsp">게시판</a></li>
</ui>
<ui class="nav navbar-nav navbar-right">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">회원관리<span class="caret"></</span></a>
<ul class="dropdown-menu">
<li><a href="logoutAction.jsp">로그아웃</a></li>
</ul></li>
</ui>
</div>
</nav>
<div class="container">
<div class="row">
<form method="post" action="updateAction.jsp?bbsID=<%=bbsID%>">
<table class="table table-striped"
style="text-align: center; border: 1px solid #dddddd">
<thead>
<tr>
<th colspan="2"
style="background-color: #eeeeee; text-align: center;">게시판 글 수정</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"
placeholder="글 제목" name="bbsTitle" maxlength="50" value="<%=bbs.getBbsTitle()%>"></td>
</tr>
<tr>
<td><textarea class="form-control" placeholder="글 내용"
name="bbsContent" maxlength="2048" style="height: 350px;"><%=bbs.getBbsContent()%>"</textarea></td>
</tr>
</tbody>
</table>
<input type="submit" class="btn btn-primary pull-right" value="글 수정">
</form>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.js"></script>
</body>
</html>
Write.jsp와 비슷하다.
다만, 기존의 글을 수정하는 것이기에 기존 글의 제목과 내용을 가져와 띄워주어야 한다.
value="<%=bbs.getBbsTitle()%>"></td>
<%=bbs.getBbsContent()%>"</textarea></td>
이렇게 띄워주어야 한다.
updateAction.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="bbs.BbsDAO" %>
<%@ page import="bbs.Bbs" %>
<%@ page import="java.io.PrintWriter"%>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>update action page</title>
</head>
<body>
<%
String userID = null;
if(session.getAttribute("userID")!=null);{
userID = (String) session.getAttribute("userID");
}
if(userID == null){
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요')");
script.println("location.href='login.jsp'");
script.println("</script>");
}
int bbsID = 0;
if (request.getParameter("bbsID") != null) {
bbsID = Integer.parseInt(request.getParameter("bbsID"));
}
if (bbsID == 0) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요.')");
script.println("location.href='bbs.jsp'");
script.println("</script>");
}
Bbs bbs = new BbsDAO().getBbs(bbsID);
if (!userID.equals(bbs.getUserID())) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('권한이 없습니다.')");
script.println("location.href='login.jsp'");
script.println("</script>");
}else{
if(request.getParameter("bbsTitle") == null || request.getParameter("bbsContent") == null || request.getParameter("bbsTitle").equals("") || request.getParameter("bbsContent").equals("")){
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('입력이 안 된 사항이 있습니다.')");
script.println("history.back()");
script.println("</script>");
}else{
BbsDAO bbsDAO = new BbsDAO();
int result = bbsDAO.update(bbsID , request.getParameter("bbsTitle"), request.getParameter("bbsContent"));
if (result==-1){
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('글 수정에 실패했습니다.')");
script.println("history.back()");
script.println("</script>");
}
else{
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("location.href = 'bbs.jsp'");
script.println("</script>");
}
}
}
%>
</body>
</html>
writeAction에서 처럼 유저의 권한과 입력사항 등을 체크해주고, 성공시와 실패시의 알고리즘을 분류해 코딩한다.
deleteAction.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="bbs.BbsDAO" %>
<%@ page import="bbs.Bbs" %>
<%@ page import="java.io.PrintWriter"%>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>update action page</title>
</head>
<body>
<%
String userID = null;
if(session.getAttribute("userID")!=null);{
userID = (String) session.getAttribute("userID");
}
if(userID == null){
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요')");
script.println("location.href='login.jsp'");
script.println("</script>");
}
int bbsID = 0;
if (request.getParameter("bbsID") != null) {
bbsID = Integer.parseInt(request.getParameter("bbsID"));
}
if (bbsID == 0) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('로그인을 하세요.')");
script.println("location.href='bbs.jsp'");
script.println("</script>");
}
Bbs bbs = new BbsDAO().getBbs(bbsID);
if (!userID.equals(bbs.getUserID())) {
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('권한이 없습니다.')");
script.println("location.href='login.jsp'");
script.println("</script>");
}else{
BbsDAO bbsDAO = new BbsDAO();
int result = bbsDAO.delete(bbsID);
if (result==-1){
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("alert('글 삭제에 실패했습니다.')");
script.println("history.back()");
script.println("</script>");
}
else{
PrintWriter script = response.getWriter();
script.println("<script>");
script.println("location.href = 'bbs.jsp'");
script.println("</script>");
}
}
%>
</body>
</html>
Update를 구현했다면 delete는 약간의 수정만 해주면 된다.
Update의 코드에 delete함수를 적용해주면 된다.