https://intheham.tistory.com/67
이어서~
글번호 / 작성일 / 작성자id / 글내용 / 사진1 / 사진2 / 사진3
<SQL>
create table diary(
num number primary key,
writer varchar2(20) references member1(id) on delete cascade,
w_date date,
content varchar2(100),
pic1 varchar2(100),
pic2 varchar2(100),
pic3 varchar2(100)
);
create sequence seq_diary;
<DiaryVo>
private int num;
private String writer;
private Date w_date;
private String content;
private String pic1;
private String pic2;
private String pic3;
package diary;
import java.sql.Date;
public class DiaryVo {
private int num;
private String writer;
private Date w_date;
private String content;
private String pic1;
private String pic2;
private String pic3;
public DiaryVo() {}
public DiaryVo(int num, String writer, Date w_date, String content, String pic1, String pic2, String pic3) {
super();
this.num = num;
this.writer = writer;
this.w_date = w_date;
this.content = content;
this.pic1 = pic1;
this.pic2 = pic2;
this.pic3 = pic3;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPic1() {
return pic1;
}
public void setPic1(String pic1) {
this.pic1 = pic1;
}
public String getPic2() {
return pic2;
}
public void setPic2(String pic2) {
this.pic2 = pic2;
}
public String getPic3() {
return pic3;
}
public void setPic3(String pic3) {
this.pic3 = pic3;
}
@Override
public String toString() {
return "DiaryVo [num=" + num + ", writer=" + writer + ", w_date=" + w_date + ", content=" + content + ", pic1="
+ pic1 + ", pic2=" + pic2 + ", pic3=" + pic3 + "]";
}
}
<DiaryDao>
public void insert(DiaryVo vo){}
public DiaryVo select(int num){}
public ArrayList<DiaryVo> selectAll(String writer){} -- 작성자 게시글 전체 검색
public void update(DiaryVo vo){} -- 글 내용 수정
public void delete(int num){}
package diary;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import conn.DBConnect;
public class DiaryDao {
private DBConnect dbconn;
public DiaryDao() {
dbconn = DBConnect.getInstance();
}
public void insert(DiaryVo vo){
Connection conn = dbconn.conn();
String sql = "insert into diary values(seq_diary.nextval, ?, sysdate, ?, ?, ?, ?)";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getWriter());
pstmt.setString(2, vo.getContent());
pstmt.setString(3, vo.getPic1());
pstmt.setString(4, vo.getPic2());
pstmt.setString(5, vo.getPic3());
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 DiaryVo select(int num){
Connection conn = dbconn.conn();
String sql = "select * from diary where num = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
return new DiaryVo(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7));
}
} 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<DiaryVo> selectAll(String writer){
ArrayList<DiaryVo> list = new ArrayList<>();
Connection conn = dbconn.conn();
String sql = "select * from diary where writer = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, writer);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
list.add(new DiaryVo(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7)));
}
} 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(DiaryVo vo){
Connection conn = dbconn.conn();
String sql = "update diary set content = ? where num = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getContent());
pstmt.setInt(2, vo.getNum());
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();
}
}
}
public void delete(int num){
Connection conn = dbconn.conn();
String sql = "delete from diary 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();
}
}
}
}
<DiaryService>
public final static String path = "/Users/ham/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps/diary/";
--- 파일을 업로드 할 경로를 아예 Service의 멤버변수로 설정함.
public void add(DiaryVo vo){
dao.insert(vo);
}
public DiaryVo getDiary(int num){
return dao.select(num);
}
public ArrayList<DiaryVo> getAll(String writer){
return dao.selectAll(writer);
}
public void editDiary(DiaryVo vo){
dao.update(vo);
}
public void delDiary(int num){
dao.delete(num);
}
package diary;
import java.util.ArrayList;
public class DiaryService {
private DiaryDao dao;
public final static String path = "/Users/ham/Desktop/web_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/webapps/diary/";
public DiaryService() {
dao = new DiaryDao();
}
public void add(DiaryVo vo){
dao.insert(vo);
}
public DiaryVo getDiary(int num){
return dao.select(num);
}
public ArrayList<DiaryVo> getAll(String writer){
return dao.selectAll(writer);
}
public void editDiary(DiaryVo vo){
dao.update(vo);
}
public void delDiary(int num){
dao.delete(num);
}
}
일기 작성
- 이미지 없을 때 대신 불러올 이미지 지정 (이름을 nopic.jpg)로 할 것!
- 이미지가 있으면 원래 이름으로 파일명 하기.
String fname1="nopic.jpg";
if(f1 != null) {
fname1 = f1.getName();
}
package diary.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 diary.DiaryService;
import diary.DiaryVo;
/**
* Servlet implementation class DiaryAdd
*/
@WebServlet("/diary/add")
public class DiaryAdd extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DiaryAdd() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// 작성폼 줌. 페이지 이동은 /index.jsp. request에 view 이름으로 경로"/diary/add.jsp"
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setAttribute("view", "/diary/add.jsp");
RequestDispatcher dis = request.getRequestDispatcher("/index.jsp");
dis.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
// 파일 업로드. 위치는 /webapps/diary. 이미지가 null인지 아닌지 판단해서 올리기.
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");
int size = 100 * 1024 * 1024; // 100M
// 업로드에 사용할 MultipartRequest 객체 생성
MultipartRequest multipart = new MultipartRequest(request, DiaryService.path, size, "UTF-8", new DefaultFileRenamePolicy());
// 폼파라메터 읽기
String writer = multipart.getParameter("writer");
String content = multipart.getParameter("content");
// 업로드된 파일의 파일객체 반환
File f1 = multipart.getFile("pic1");
File f2 = multipart.getFile("pic2");
File f3 = multipart.getFile("pic3");
// 이미지 없을 때 대신 불러올 이미지 지정 (이름을 nopic.jpg로 할 것)
String fname1="nopic.jpg";
String fname2="nopic.jpg";
String fname3="nopic.jpg";
// 이미지가 있으면 원래 이름으로 해라~
if(f1 != null) {
fname1 = f1.getName();
}
if(f2 != null) {
fname2 = f2.getName();
}
if(f3 != null) {
fname3 = f3.getName();
}
DiaryService service = new DiaryService();
service.add(new DiaryVo(0, writer, null, content, fname1, fname2, fname3));
response.sendRedirect(request.getContextPath()+"/diary/list");
}
}
<%@ 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}/diary/add" method="post" enctype="multipart/form-data">
<input type="hidden" name="writer" value="${sessionScope.loginId }">
<table border="1">
<tr>
<th>오늘의 일기</th>
<td><textarea name="content" rows="5" cols="30">내용 입력</textarea></td>
</tr>
<tr>
<th>사진</th>
<td><input type="file" name="pic1"><br/>
<input type="file" name="pic2"><br/>
<input type="file" name="pic3"><br/>
</td>
</tr>
<tr>
<th>저장</th>
<td><input type="submit" value="저장"></td>
</tr>
</table>
</form>
</body>
</html>
일기 목록 보기
package diary.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 javax.servlet.http.HttpSession;
import diary.DiaryService;
import diary.DiaryVo;
/**
* Servlet implementation class DiaryList
*/
@WebServlet("/diary/list")
public class DiaryList extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DiaryList() {
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
// 현재 세션 열기
// false = 기존에 있는 세션 가져와라. 없으면 세션 새로 만들지 말고 차라리 error 떠라.
HttpSession session = request.getSession(false);
String writer = (String)session.getAttribute("loginId");
DiaryService service = new DiaryService();
ArrayList<DiaryVo> list = service.getAll(writer);
request.setAttribute("list", list); // 뷰페이지에서 ${}로 불러올려구~
request.setAttribute("view", "/diary/list.jsp"); // 이동할 뷰페이지
RequestDispatcher dis = request.getRequestDispatcher("/index.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);
}
}
<%@ 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>
</head>
<body>
<h3>일기 목록</h3>
<table border=1>
<tr>
<th>날짜</th>
</tr>
<c:forEach var="vo" items="${list}">
<tr>
<td><a href="${pageContext.request.contextPath}/diary/detail?num=${vo.num}">${vo.w_date}</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
일기 상세 보기 & 수정
- 수정메소드를 MyInfo.java의 doPost()에 구현해놨으니까 post 방식으로 가야함!
let param = "num=" + num;
param += "&content=" + document.getElementById("content").value;
xhttp.open("POST", "${pageContext.request.contextPath}/diary/detail");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
package diary.controller;
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 org.json.simple.JSONObject;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import diary.DiaryService;
import diary.DiaryVo;
/**
* Servlet implementation class DiaryDetail
*/
@WebServlet("/diary/detail")
public class DiaryDetail extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DiaryDetail() {
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
int num = Integer.parseInt(request.getParameter("num"));
DiaryService service = new DiaryService();
DiaryVo vo = service.getDiary(num);
request.setAttribute("vo", vo);
request.setAttribute("view", "/diary/detail.jsp"); // 이동할 뷰페이지
RequestDispatcher dis = request.getRequestDispatcher("/index.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");
int num = Integer.parseInt(request.getParameter("num"));
String content = request.getParameter("content");
DiaryService service = new DiaryService();
service.editDiary(new DiaryVo(num, null, null, content, null, null, null));
DiaryVo vo = service.getDiary(num);
String txt = vo.getContent();
response.getWriter().append(txt);
}
}
<%@ 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>
<style>
img{
width:400px;
height:200px;
}
</style>
<script>
function edit(num){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
document.getElementById("res").innerHTML = '<a style="color:blue">수정 완료</a>';
}
let param = "num=" + num;
param += "&content=" + document.getElementById("content").value;
xhttp.open("POST", "${pageContext.request.contextPath}/diary/detail");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
</script>
</head>
<body>
<h3 style="text-align:center">${vo.w_date}의 일기</h3>
<form name="f" action="${pageContext.request.contextPath}/diary/detail" method="post">
<input type ="hidden" value="${vo.num }" name="num">
<table border="1">
<tr><td><img src="/diary/${vo.pic1}"><br/><img src="/diary/${vo.pic2}"><br/><img src="/diary/${vo.pic3}"></td></tr>
<tr><td><textarea id="content" cols="48" rows="10">${vo.content}</textarea></td></tr>
</table>
<input type="button" value="수정" onclick="edit(${vo.num })">
<input type="button" value="삭제" onclick="location.href='${pageContext.request.contextPath}/diary/delete?num=${vo.num }'">
<span id="res"></span>
</form>
</body>
</html>
일기 삭제
- num으로 삭제할 일기 select 하기
- 이미지 파일 경로(Service에서 멤버변수로 선언)에 이미지 이름 덧붙이기
- 덧붙인 경로로 파일 불러오기 ------- 이미지가 3개니까 3개 하기~
- 이미지를 업로드하지 않았을 때 대신 띄울 nopic.jpg는 지우면 안됨! (계속 불러와야 하니까)
==> nopic.jpg 아닌 경우에만 이미지 파일 지우도록 if 조건문 수행.
if(! vo.getPic1().equals("nopic.jpg")) {
f1.delete();
}
- service 삭제 메소드로 db 삭제
package diary.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 diary.DiaryService;
import diary.DiaryVo;
/**
* Servlet implementation class DiaryDelete
*/
@WebServlet("/diary/delete")
public class DiaryDelete extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DiaryDelete() {
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 = DiaryService.path;
int num = Integer.parseInt(request.getParameter("num"));
DiaryService service = new DiaryService();
DiaryVo vo = service.getDiary(num);
// 이미지 파일 경로에 이미지 이름 덧붙이기
String delPath1 = path+vo.getPic1();
String delPath2 = path+vo.getPic2();
String delPath3 = path+vo.getPic3();
// 덧붙인 경로로 파일 불러오기
File f1 = new File(delPath1);
File f2 = new File(delPath2);
File f3 = new File(delPath3);
// 이미지를 업로드하지 않았을 때 대신 띄울 nopic 이미지는 지우면 안되니까 nopic 아닐 때에만 이미지파일 지우기!
if(! vo.getPic1().equals("nopic.jpg")) {
f1.delete();
}
if(! vo.getPic2().equals("nopic.jpg")) {
f2.delete();
}
if(! vo.getPic3().equals("nopic.jpg")) {
f3.delete();
}
service.delDiary(num); // db 삭제
response.sendRedirect(request.getContextPath()+"/diary/list");
}
/**
* @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);
}
}