1. 리스트에서 수정폼 띄워서 수정 (상세페이지X)
- 리스트는 상세페이지처럼 값이 고정되어있지 않음.
- 그래서 태그에 id를 "a_${vo.num}" 처럼 두고 호출 메서드에 파라메터로 ${vo.num}을 넣어야 함.
@WebServlet("/imgboard/list")
public class ImgBoardList extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ImgBoardService service = new ImgBoardService();
ImgRepService serv = new ImgRepService();
ArrayList<ImgBoardVo> list = service.getAll(); // 원글 전체 검색
for (ImgBoardVo vo : list) { // 전체 원글을 하나씩 vo에 꺼내서
// 원글(vo)의 글번호로 등록되어 있는 댓글을 검색해 하나씩 reps에 담음.
ArrayList<ImgRepVo> reps = serv.getReps(vo.getNum());
vo.setReps(reps); //꺼낸 댓글을 ImgBoardVo 의 ArrayList<ImgRepVo>reps멤버변수에 넣음.
}
request.setAttribute("list", list);
RequestDispatcher dis = request.getRequestDispatcher("/imgboard/list.jsp");
dis.forward(request, response);
}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script>
function editForm(num){ // 수정폼 띄우기
let el = document.getElementById("editf_"+num);
el.style.display="";
}
function cancle(num){ // 수정폼 사라지기
let el = document.getElementById("editf_"+num);
el.style.display="none";
}
function edit(num){ // db 및 뷰 수정
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let obj = JSON.parse(xhttp.responseText);
document.getElementById("title_"+num).innerHTML = obj.title;
document.getElementById("cont_"+num).innerHTML = obj.content;
cancle(num);
}
let param = "?num=" + num;
param += "&title=" + document.getElementById("eval1_"+num).value;
param += "&content=" + document.getElementById("eval2_"+num).value;
xhttp.open("GET", "${pageContext.request.contextPath}/imgboard/edit"+param);
xhttp.send();
}
</script>
</head>
<body>
<c:forEach var="vo" items="${list}">
<table border="1" id="tbl_${vo.num}">
<tr>
<th>num</th>
<td>${vo.num}
<c:if test="${sessionScope.loginId == vo.writer}"> <!-- Id와 작성자가 같으면 -->
<input type="button" value="수정" onclick="editForm(${vo.num})">
<input type="button" value="삭제" onclick="del(${vo.num})">
<form id="editf_${vo.num}" style="display: none"> <!-- 수정버튼 누르면 보이기 -->
new title:<input type="text" id="eval1_${vo.num}" value="${vo.title}"><br/>
new content:<input type="text" id="eval2_${vo.num}" value="${vo.content}"><br />
<input type="button" value="수정완료" onclick="edit(${vo.num})">
<input type="button" value="취소" onclick="cancle(${vo.num})">
</form>
</c:if>
</td>
</tr>
<tr>
<th>title</th>
<td><span id="title_${vo.num}">${vo.title}</span></td>
</tr>
<tr>
<th>content</th>
<td><textarea rows="10" cols="30"
id="cont_${vo.num}">${vo.content}</textarea></td>
</tr>
</table>
</c:forEach>
</body>
@WebServlet("/imgboard/edit")
public class ImgBoardEdit extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
int num = Integer.parseInt(request.getParameter("num"));
String title = request.getParameter("title");
String content = request.getParameter("content");
ImgBoardService service = new ImgBoardService();
service.editImg(new ImgBoardVo(num, null, null, title, content, null));
ImgBoardVo vo = service.getImg(num);
JSONObject obj = new JSONObject();
obj.put("title", vo.getTitle());
obj.put("content", vo.getContent());
String txt = obj.toJSONString();
response.getWriter().append(txt);
}
}
2. AJAX로 삭제. (db 삭제와 화면에서 안보이게 처리)
<head>
<script>
function del(num){
const xhttp = new XMLHttpRequest();
// db에서 데이터 지우기
let param = "?num=" + num;
xhttp.open("GET", "${pageContext.request.contextPath}/imgboard/delete"+param);
xhttp.send();
// 화면에서 데이터 지우기
let body = document.getElementsByTagName("body")[0];
let deltbl = document.getElementById("tbl_"+num);
body.removeChild(deltbl);
}
</script>
</head>
<body>
<c:forEach var="vo" items="${list}">
<table border="1" id="tbl_${vo.num}">
<tr>
<th>num</th>
<td>${vo.num}
<c:if test="${sessionScope.loginId == vo.writer}">
<input type="button" value="수정" onclick="editForm(${vo.num})">
<input type="button" value="삭제" onclick="del(${vo.num})">
</c:if>
</td>
</tr>
</table>
</c:forEach>
</body>
@WebServlet("/imgboard/delete")
public class ImgBoardDel extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = "/Users/~~~/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps";
int num = Integer.parseInt(request.getParameter("num"));
ImgBoardService service = new ImgBoardService();
ImgBoardVo vo = service.getImg(num);
//vo.getPath() : /img/이미지이름
//ImgBoardAdd 에서 -- String fname = "/img/"+f.getName();// 웹 경로 + 파일명 째로 path에 담음~
String delf = path+vo.getPath();
System.out.println(delf);
File f = new File(delf);
f.delete(); // 이미지 파일 삭제
service.delImg(num); // db 삭제
}
}
3. 리스트에서 댓글 쓰기 (상세페이지X)
<head>
<script>
function comAdd(num){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let arr = JSON.parse(xhttp.responseText);
let html = '';
for(let obj of arr){ // 댓글 추가한 db for문으로 처음부터 돌림
html += obj.content+" (writer: "+obj.writer+")<br/>";
}
let div = document.getElementById("r_"+num);
div.innerHTML = html;
document.getElementById("rep_"+num).value = ''; // 댓글작성창 초기화
}
let param = "?pnum=" + num;
param += "&writer=${sessionScope.loginId}";
param += "&content=" + document.getElementById("rep_"+num).value;
xhttp.open("GET", "${pageContext.request.contextPath}/imgrep/add"+param);
xhttp.send();
}
</script>
</head>
<body>
<c:forEach var="vo" items="${list}">
<table border="1" id="tbl_${vo.num}">
<tr>
<th>comment</th>
<td><input type="text" id="rep_${vo.num}">
<input type="button" value="작성" onclick="comAdd(${vo.num})">
<div id="r_${vo.num}">
<c:forEach var="rep" items="${vo.reps}">
${rep.content} (writer:${rep.writer}) <br/> <!-- 기존 db 댓글 -->
</c:forEach>
</div>
</td>
</tr>
</table>
</c:forEach>
</body>
@WebServlet("/imgrep/add")
public class ImgRepAdd extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
int pnum = Integer.parseInt(request.getParameter("pnum")); //원글번호
String writer = request.getParameter("writer");
String content = request.getParameter("content");
ImgRepService service = new ImgRepService();
service.addRep(new ImgRepVo(0, pnum, writer, content));
ArrayList<ImgRepVo> reps = service.getReps(pnum); //원글 번호로 원글에 달린 댓글 전부 불러오기
JSONArray arr = new JSONArray();
for (ImgRepVo vo:reps) {
JSONObject obj = new JSONObject();
obj.put("writer", vo.getWriter());
obj.put("content", vo.getContent());
arr.add(obj);
}
String txt = arr.toJSONString();
response.getWriter().append(txt);
}
}
4. 이미지 게시판 글쓰기
<input type="button" value="글작성"
onclick="location.href='${pageContext.request.contextPath}/imgboard/add'">
@WebServlet("/imgboard/add")
public class ImgBoardAdd extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dis = request.getRequestDispatcher("/imgboard/add.jsp");
dis.forward(request, response);
}
}
<h3>글작성</h3>
<form action = "${pageContext.request.contextPath}/imgboard/add" method = "post" enctype="multipart/form-data">
<table border = "1">
<tr><th>작성자</th><td><input type = "text" name = "writer" value="${sessionScope.loginId}" readonly></td></tr>
<tr><th>제목</th><td><input type = "text" name = "title"></td></tr>
<tr><th>내용</th><td><textarea name = "content" rows="20" cols="30">내용을 입력해주세요.</textarea></td></tr>
<tr><th>사진</th><td><input type="file" name="file"></td></tr>
</table>
<input type = "submit" value="작성">
</form>
@WebServlet("/imgboard/add")
public class ImgBoardAdd extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
// 업로드 할 경로
String path = "/Users/~~~~~/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps/img/";
// 업로드 파일의 최대 크기
int size = 100 * 1024 * 1024; // 100M
// 업로드에 사용할 MultipartRequest 객체 생성
MultipartRequest multipart = new MultipartRequest(request, path, size, "UTF-8", new DefaultFileRenamePolicy());
// 폼파라메터 읽기
String writer = multipart.getParameter("writer");
String title = multipart.getParameter("title");
String content = multipart.getParameter("content");
// 업로드된 파일의 파일객체 반환
File f = multipart.getFile("file");
// getName(): 파일명 반환
// 윈도우는 "\\img\\" 맥은 "/img/"
String fname = "/img/"+f.getName();// 웹 경로 + 파일명 째로 vo에 담음~
ImgBoardService service = new ImgBoardService();
service.addImg(new ImgBoardVo(0, writer, null, title, content, fname));
response.sendRedirect(request.getContextPath()+"/imgboard/list");
}
}
0. 총 코드
* list.jsp
더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function comAdd(num){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let arr = JSON.parse(xhttp.responseText);
let html = '';
for(let obj of arr){ /* 자바스크립트의 반복자. of -- 값 꺼내기 */
html += obj.content+" (writer: "+obj.writer+")<br/>";
}
let div = document.getElementById("r_"+num);
div.innerHTML = html;
document.getElementById("rep_"+num).value = '';
}
let param = "?pnum=" + num;
param += "&writer=${sessionScope.loginId}";
param += "&content=" + document.getElementById("rep_"+num).value;
xhttp.open("GET", "${pageContext.request.contextPath}/imgrep/add"+param);
xhttp.send();
}
function editForm(num){
let el = document.getElementById("editf_"+num);
el.style.display="";
}
function cancle(num){
let el = document.getElementById("editf_"+num);
el.style.display="none";
}
function edit(num){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let obj = JSON.parse(xhttp.responseText);
document.getElementById("title_"+num).innerHTML = obj.title;
document.getElementById("cont_"+num).innerHTML = obj.content;
cancle(num);
}
let param = "?num=" + num;
param += "&title=" + document.getElementById("eval1_"+num).value;
param += "&content=" + document.getElementById("eval2_"+num).value;
xhttp.open("GET", "${pageContext.request.contextPath}/imgboard/edit"+param);
xhttp.send();
}
function del(num){
const xhttp = new XMLHttpRequest();
// db에서 데이터 지우기
let param = "?num=" + num;
xhttp.open("GET", "${pageContext.request.contextPath}/imgboard/delete"+param);
xhttp.send();
// 화면에서 데이터 지우기
let body = document.getElementsByTagName("body")[0];
let deltbl = document.getElementById("tbl_"+num);
body.removeChild(deltbl);
}
</script>
</head>
<body>
<h3>이미지 게시판</h3>
<input type="button" value="글작성"
onclick="location.href='${pageContext.request.contextPath}/imgboard/add'">
<input type="button" value="홈화면"
onclick="location.href='${pageContext.request.contextPath}/index.jsp'">
<c:forEach var="vo" items="${list}">
<table border="1" id="tbl_${vo.num}">
<tr>
<th>num</th>
<td>${vo.num}
<c:if test="${sessionScope.loginId == vo.writer}">
<input type="button" value="수정" onclick="editForm(${vo.num})">
<input type="button" value="삭제" onclick="del(${vo.num})">
<form id="editf_${vo.num}" style="display: none">
new title:<input type="text" id="eval1_${vo.num}" value="${vo.title}"><br/>
new content:<input type="text" id="eval2_${vo.num}" value="${vo.content}"><br />
<input type="button" value="수정완료" onclick="edit(${vo.num})">
<input type="button" value="취소" onclick="cancle(${vo.num})">
</form>
</c:if>
</td>
</tr>
<tr>
<th>w_date</th>
<td>${vo.w_date}</td>
</tr>
<tr>
<th>writer</th>
<td>${vo.writer}</td>
</tr>
<tr>
<th>title</th>
<td><span id="title_${vo.num}">${vo.title}</span></td>
</tr>
<tr>
<th>image</th>
<td><img src="${vo.path}"
style="width: 200px; height: 200px" name=img></td>
</tr>
<tr>
<th>content</th>
<td><textarea rows="10" cols="30"
id="cont_${vo.num}">${vo.content}</textarea></td>
</tr>
<tr>
<th>comment</th>
<td><input type="text" id="rep_${vo.num}"><input
type="button" value="작성" onclick="comAdd(${vo.num})">
<div id="r_${vo.num}">
<c:forEach var="rep" items="${vo.reps}">
${rep.content} (writer:${rep.writer}) <br />
</c:forEach>
</div></td>
</tr>
</table>
</c:forEach>
</body>
</html>
* add.jsp
더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>글작성</h3>
<form action = "${pageContext.request.contextPath}/imgboard/add" method = "post" enctype="multipart/form-data">
<table border = "1">
<tr><th>작성자</th><td><input type = "text" name = "writer" value="${sessionScope.loginId}" readonly></td></tr>
<tr><th>제목</th><td><input type = "text" name = "title"></td></tr>
<tr><th>내용</th><td><textarea name = "content" rows="20" cols="30">내용을 입력해주세요.</textarea></td></tr>
<tr><th>사진</th><td><input type="file" name="file"></td></tr>
</table>
<input type = "submit" value="작성">
</form>
</body>
</html>
<이미지 게시글>
* ImgBoardAdd.java
더보기
package imgboard.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import imgboard.ImgBoardService;
import imgboard.ImgBoardVo;
/**
* Servlet implementation class ImgBoardAdd
*/
@WebServlet("/imgboard/add")
public class ImgBoardAdd extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgBoardAdd() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
RequestDispatcher dis = request.getRequestDispatcher("/imgboard/add.jsp");
dis.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
// 업로드 할 경로
String path = "/Users/choeyeeun/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps/img/";
// 업로드 파일의 최대 크기
int size = 100 * 1024 * 1024; // 100M
// 업로드에 사용할 MultipartRequest 객체 생성
MultipartRequest multipart = new MultipartRequest(request, path, size, "UTF-8", new DefaultFileRenamePolicy());
// 폼파라메터 읽기
String writer = multipart.getParameter("writer");
String title = multipart.getParameter("title");
String content = multipart.getParameter("content");
// 업로드된 파일의 파일객체 반환
File f = multipart.getFile("file");
// getName(): 파일명 반환
// 윈도우는 "\\img\\" 맥은 "/img/"
String fname = "/img/"+f.getName();// 웹 경로 + 파일명 째로 vo에 담음~
ImgBoardService service = new ImgBoardService();
service.addImg(new ImgBoardVo(0, writer, null, title, content, fname));
response.sendRedirect(request.getContextPath()+"/imgboard/list");
}
}
* ImgBoardDel.java
더보기
package imgboard.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import imgboard.ImgBoardService;
import imgboard.ImgBoardVo;
/**
* Servlet implementation class ImgBoardDel
*/
@WebServlet("/imgboard/delete")
public class ImgBoardDel extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgBoardDel() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String path = "/Users/choeyeeun/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps";
int num = Integer.parseInt(request.getParameter("num"));
ImgBoardService service = new ImgBoardService();
ImgBoardVo vo = service.getImg(num);
//vo.getPath() : /img/이미지이름
//ImgBoardAdd 에서 -- String fname = "/img/"+f.getName();// 웹 경로 + 파일명 째로 path에 담음~
String delf = path+vo.getPath();
System.out.println(delf);
File f = new File(delf);
f.delete(); // 이미지 파일 삭제
service.delImg(num); // db 삭제
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
* ImgBoardEdit.java
더보기
package imgboard.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import imgboard.ImgBoardService;
import imgboard.ImgBoardVo;
/**
* Servlet implementation class ImgBoardEdit
*/
@WebServlet("/imgboard/edit")
public class ImgBoardEdit extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgBoardEdit() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
int num = Integer.parseInt(request.getParameter("num"));
String title = request.getParameter("title");
String content = request.getParameter("content");
ImgBoardService service = new ImgBoardService();
service.editImg(new ImgBoardVo(num, null, null, title, content, null));
ImgBoardVo vo = service.getImg(num);
JSONObject obj = new JSONObject();
obj.put("title", vo.getTitle());
obj.put("content", vo.getContent());
String txt = obj.toJSONString();
response.getWriter().append(txt);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
* ImgBoardList.java
더보기
package imgboard.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import imgboard.ImgBoardService;
import imgboard.ImgBoardVo;
import imgreps.ImgRepService;
import imgreps.ImgRepVo;
/**
* Servlet implementation class ImgBoardList
*/
@WebServlet("/imgboard/list")
public class ImgBoardList extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgBoardList() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ImgBoardService service = new ImgBoardService();
ImgRepService serv = new ImgRepService();
ArrayList<ImgBoardVo> list = service.getAll(); // 원글 전체 검색
for (ImgBoardVo vo : list) { // 전체 원글을 하나씩 vo에 꺼내서
// 원글(vo)의 글번호로 등록되어 있는 댓글을 검색해 하나씩 reps에 담음.
ArrayList<ImgRepVo> reps = serv.getReps(vo.getNum());
vo.setReps(reps); //꺼낸 댓글을 ImgBoardVo 의 ArrayList<ImgRepVo>reps멤버변수에 넣음.
}
request.setAttribute("list", list);
RequestDispatcher dis = request.getRequestDispatcher("/imgboard/list.jsp");
dis.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
* ImgBoardVo
더보기
package imgboard;
import java.sql.Date;
import java.util.ArrayList;
import imgreps.ImgRepVo;
public class ImgBoardVo {
private int num;
private String writer;
private Date w_date;
private String title;
private String content;
private String path;
private ArrayList<ImgRepVo> reps;
// 글이 생성될 때 덧글까지 같이 생성되지 않으니까 생성자에는 넣지 않는 걸로~
public ImgBoardVo() {}
public ImgBoardVo(int num, String writer, Date w_date, String title, String content, String path) {
super();
this.num = num;
this.writer = writer;
this.w_date = w_date;
this.title = title;
this.content = content;
this.path = path;
}
public ArrayList<ImgRepVo> getReps() {
return reps;
}
public void setReps(ArrayList<ImgRepVo> reps) {
this.reps = reps;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public Date getW_date() {
return w_date;
}
public void setW_date(Date w_date) {
this.w_date = w_date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "ImgBoardVo [num=" + num + ", writer=" + writer + ", w_date=" + w_date + ", title=" + title
+ ", content=" + content + ", path=" + path + "]";
}
}
* ImgBoardDao
더보기
package imgboard;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import conn.DBConnect;
import member.MemberVo;
public class ImgBoardDao {
private DBConnect dbconn;
public ImgBoardDao() {
dbconn = DBConnect.getInstance();
}
public void insert(ImgBoardVo vo) {
Connection conn = dbconn.conn();
String sql = "insert into imgboard values(seq_imgboard.nextval, ?, sysdate, ?, ?, ?)";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getWriter());
pstmt.setString(2, vo.getTitle());
pstmt.setString(3, vo.getContent());
pstmt.setString(4, vo.getPath());
int num = pstmt.executeUpdate();
System.out.println(num + "줄이 추가되었습니다.");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public ImgBoardVo select(int num) {
Connection conn = dbconn.conn();
String sql = "select * from imgboard where num = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
ResultSet rs = pstmt.executeQuery(); // select 실행
if (rs.next()) { // 첫 줄로 이동하여 데이터 있는지 확인
return new ImgBoardVo(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getString(4), rs.getString(5), rs.getString(6));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public ArrayList<ImgBoardVo> selectAll() {
ArrayList<ImgBoardVo> list = new ArrayList<>();
Connection conn = dbconn.conn();
String sql = "select * from imgboard order by num desc";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(); // select 실행
while (rs.next()) { // 첫 줄로 이동하여 데이터 있는지 확인
list.add(new ImgBoardVo(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getString(4), rs.getString(5), rs.getString(6)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
public void update(ImgBoardVo vo) {
Connection conn = dbconn.conn();
String sql = "update imgboard set title = ?, content = ? where num = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getTitle());
pstmt.setString(2, vo.getContent());
pstmt.setInt(3, vo.getNum());
int num = pstmt.executeUpdate();
System.out.println(num + "줄이 수정되었습니다.");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void delete(int num) {
Connection conn = dbconn.conn();
String sql = "delete from imgBoard where num = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
int number = pstmt.executeUpdate();
System.out.println(number + "줄이 삭제되었습니다.");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
* ImgBoardService
더보기
package imgboard;
import java.util.ArrayList;
public class ImgBoardService {
private ImgBoardDao dao;
public ImgBoardService() {
dao = new ImgBoardDao();
}
public void addImg(ImgBoardVo vo) {
dao.insert(vo);
}
public ImgBoardVo getImg(int num) {
return dao.select(num);
}
public ArrayList<ImgBoardVo> getAll(){
return dao.selectAll();
}
public void editImg(ImgBoardVo vo) {
dao.update(vo);
}
public void delImg(int num) {
dao.delete(num);
}
}
<이미지 게시글 댓글>
* ImgRepAdd.java
더보기
package imgreps.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import imgreps.ImgRepService;
import imgreps.ImgRepVo;
/**
* Servlet implementation class ImgRepAdd
*/
@WebServlet("/imgrep/add")
public class ImgRepAdd extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgRepAdd() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
int pnum = Integer.parseInt(request.getParameter("pnum")); //원글번호
String writer = request.getParameter("writer");
String content = request.getParameter("content");
ImgRepService service = new ImgRepService();
service.addRep(new ImgRepVo(0, pnum, writer, content));
ArrayList<ImgRepVo> reps = service.getReps(pnum); //원글 번호로 원글에 달린 댓글 전부 불러오기
JSONArray arr = new JSONArray();
for (ImgRepVo vo:reps) {
JSONObject obj = new JSONObject();
obj.put("writer", vo.getWriter());
obj.put("content", vo.getContent());
arr.add(obj);
}
String txt = arr.toJSONString();
response.getWriter().append(txt);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
* ImgRepVo
더보기
package imgreps;
public class ImgRepVo {
private int num;
private int pnum;
private String writer;
private String content;
public ImgRepVo() {}
public ImgRepVo(int num, int pnum, String writer, String content) {
super();
this.num = num;
this.pnum = pnum;
this.writer = writer;
this.content = content;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "ImgRepVo [num=" + num + ", pnum=" + pnum + ", writer=" + writer + ", content=" + content + "]";
}
}
* ImgRepDao
더보기
package imgreps;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import conn.DBConnect;
import imgboard.ImgBoardVo;
public class ImgRepDao {
private DBConnect dbconn;
public ImgRepDao() {
dbconn = DBConnect.getInstance();
}
public void insert(ImgRepVo vo) {
Connection conn = dbconn.conn();
String sql = "insert into img_reps values(seq_img_reps.nextval, ?, ?, ?)";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, vo.getPnum());
pstmt.setString(2, vo.getWriter());
pstmt.setString(3, vo.getContent());
int num = pstmt.executeUpdate();
System.out.println(num + "줄이 추가되었습니다.");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public ArrayList<ImgRepVo> selectByPnum(int num) {
ArrayList<ImgRepVo> list = new ArrayList<>();
Connection conn = dbconn.conn();
String sql = "select * from img_reps where pnum=? order by num desc";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
ResultSet rs = pstmt.executeQuery(); // select 실행
while (rs.next()) { // 첫 줄로 이동하여 데이터 있는지 확인
list.add(new ImgRepVo(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
}
* ImgRepService
더보기
package imgreps;
import java.util.ArrayList;
public class ImgRepService {
private ImgRepDao dao;
public ImgRepService() {
dao = new ImgRepDao();
}
public void addRep(ImgRepVo vo) {
dao.insert(vo);
}
public ArrayList<ImgRepVo> getReps(int pnum){
return dao.selectByPnum(pnum);
}
}