▼ 눈물이 차올랐던 어제까지의 이야기
어제 맥북의 오류를 해결했다.. 임포트를 잘 못 한거였음.
그런데.. 파일 업로드부터 cos.jar 라이브러리를 쓰는 파일들을 또 작동이 되지 않는다..ㅠ
맥으로 어떻게 공부를 해야할까.. 코드에 문제가 없으면 대부분 라이브러리나 경로 설정의 문제라고 한다. 그런데 두 가지를 체크해봐도 이상이 없어서 뭐가 문제인지 정말 알 수가 없다.. !
주말동안 코드를 옮겨 적어보며 뭐가 문제인지 다시 차분하게 체크를 해봐야겠다.
💡 이클립스는 파일이름이나 변수명을 함부로 바꾸면 그때부터 오류가 날 확률이 높아진다..!
💡 Windows 로고 키 + Prt Sc 키를 동시에 누르면 화면이 1초 정도 깜박인 후
내PC→ 사진 → 스크린샷 폴더에 이미지가 자동으로 저장
🛠 더 알아볼 것
- 어플리케이션 내장 객체의 쓰임, 활용
- 업로드는 메타데이터 폴더에 파일 업로드하는 것 까지만 하면 되는 거였음.
- 맥에서는 다운로드 목록이 안보인다. 이 부분 확인할 것.
💡 이제는 주소값으로 파라메터를 가지고 온다!!!! 그렇기 때문에 주소값이 중요하다.
모델2방식 → 게시판을 만들 때 작성했던 List.jsp 파일의 코드들을 ListControllar에 옮긴다.
모델2방식으로 게시판을 만들기 위해 작성한 파일들
- java Resources > model2.board > MVCBoardDAO.java
- java Resources > model2.board > MVCBoardDTO.java
- java Resources > model2.mvcboard > ListControllar.java
- webapp > MVCBoard > index.jsp
- webapp > MVCBoard > List.jsp
- webapp > MVCBoard > Edit.jsp
- webapp > MVCBoard > Pass.jsp
- webapp > MVCBoard > View.jsp
- webapp > MVCBoard > Write.jsp
- model2.mvcboard > Downloadcontroller
- model2.mvcboard > Editcontroller
- model2.mvcboard > Listcontroller
- model2.mvcboard > Passcontroller
- model2.mvcboard > Viewcontroller
- model2.mvcboard > Writecontroller
JSFunction 도 수정했다.
구현한 기능들은 기존의 게시판 만들기를 했을 때 했던 것과 거의 똑같다.
🌀 DB와 연결해 구현한 기능들을 수행해주는 DAO와 DTO
MVCBoardDAO.java
package model2.board;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import common.DBConnPool;
import model1.board.BoardDTO;
public class MVCBoardDAO extends DBConnPool{
// 검색 조건에 맞는 게시물의 개수를 반환합니다.
public int selectCount(Map<String , Object> map) {
int totalCount = 0;
String query = "select count(*)"
+" from mvcboard ";
if(map.get("searchWord") != null) {
query += " where " + map.get("searchField")
+ " like '%" + map.get("searchWord") + "%' ";
}
try {
psmt = con.prepareStatement(query);
rs = psmt.executeQuery();
if(rs.next()) {
totalCount = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return totalCount;
}
// 검색 조건에 맞는 게시물 목록을 반환합니다(페이징 기능 지원).
public List<MVCBoardDTO> selectListPage (Map<String , Object> map){
List<MVCBoardDTO> board = new ArrayList<>();
String query = " select * "
+ " from ( "
+ " select rownum rNum, Tb.* "
+ " from ( "
+ " select * "
+ " from mvcboard ";
if(map.get("searchWord") != null) {
query += " where " + map.get("searchField")
+ " like '%" + map.get("searchWord") + "%' ";
}
query += " order by idx desc"
+ " ) Tb "
+ " ) "
+ " where rnum between ? and ? ";
// 페이징을 하기 위한 조건인 물음표 두개
try {
psmt = con.prepareStatement(query);
psmt.setString(1, map.get("start").toString());
psmt.setString(2, map.get("end").toString());
rs = psmt.executeQuery();
while(rs.next()) {
MVCBoardDTO dto = new MVCBoardDTO();
dto.setIdx(rs.getString("idx"));
dto.setName(rs.getString("Name"));
dto.setTitle(rs.getString("title"));
dto.setContent(rs.getString("content"));
dto.setPostDate(rs.getString("postdate"));
dto.setOfile(rs.getString("Ofile"));
dto.setSfile(rs.getString("Sfile"));
dto.setDowncount(rs.getInt("downcount"));
dto.setPass(rs.getString("Pass"));
dto.setVisitcount(rs.getInt("Visitcount"));
/*
* System.out.println(rs.getString("idx"));
* System.out.println(rs.getString("Name"));
*/
board.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
}
return board;
}
// 게시글 데이터를 받아 DB에 추가합니다(파일 업로드 지원).
public int insertWrite(MVCBoardDTO dto) {
int result = 0;
String query = "insert into mvcboard" //select into 는 새로운 정보를 삽입할 때 사용
+ " (idx, name, title, content, ofile, sfile, pass) "
+ " values ( seq_board_num.nextval, ?,?,?,?,?,?) ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, dto.getName());
psmt.setString(2, dto.getTitle());
psmt.setString(3, dto.getContent());
psmt.setString(4, dto.getOfile());
psmt.setString(5, dto.getSfile());
psmt.setString(6, dto.getPass());
result = psmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// 주어진 일련번호에 해당하는 게시물을 DTO에 담아 반환합니다.
public MVCBoardDTO selectView(String idx) {
MVCBoardDTO dto = new MVCBoardDTO();
String query = " select * from mvcboard where idx=? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, idx);
rs = psmt.executeQuery();
if(rs.next()) {
dto.setIdx(rs.getString("idx"));
dto.setName(rs.getString("Name"));
dto.setTitle(rs.getString("title"));
dto.setContent(rs.getString("content"));
dto.setPostDate(rs.getString("postdate"));
dto.setOfile(rs.getString("Ofile"));
dto.setSfile(rs.getString("Sfile"));
dto.setDowncount(rs.getInt("downcount"));
dto.setPass(rs.getString("Pass"));
dto.setVisitcount(rs.getInt("Visitcount"));
}
}catch (Exception e) {
System.out.println("게시물 조회 증가 중 예외발생");
e.printStackTrace();
}
return dto;
}
// 주어진 일련번호에 해당하는 게시물의 조회수를 1 증가시킵니다.
public void updateVisitCount(String idx) {
String query = " update mvcboard "
+ " set visitcount = visitcount + 1 "
+ " where idx = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, idx);
psmt.executeQuery();
}catch (Exception e) {
e.printStackTrace();
}
}
// 다운로드 횟수를 1 증가시킵니다.
public void downCountPlus(String idx) {
String query = " update mvcboard "
+ " set downcount = downcount + 1 "
+ " where idx = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, idx);
psmt.executeQuery();
}catch (Exception e) {
System.out.println("파일 다운로드 수 증가 중 예외발생");
e.printStackTrace();
}
}
// 입력한 비밀번호가 지정한 일련번호의 게시물의 비밀번호와 일치하는지 확인합니다.
public boolean confirmPassword(String pass, String idx) {
boolean flag = true;
// 아이디, 패스워드가 일치하면 true
String query = " select count(*) from mvcboard "
+ " where pass = ? and idx = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, pass);
psmt.setString(2, idx);
rs= psmt.executeQuery();
rs.next();
if (rs.getInt(1) == 0) {
flag = false;
}
} catch (Exception e) {
System.out.println("비밀번호 확인 중 예외발생");
e.printStackTrace();
}
return flag;
}
// 지정한 일련번호의 게시물을 삭제합니다.
public int deletePost(String idx) {
int result = 0;
String query = " delete from mvcboard where idx = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, idx);
result = psmt.executeUpdate();
}catch (Exception e) {
System.out.println("게시물 삭제 중 예외발생");
e.printStackTrace();
}
return result;
}
// 게시글 데이터를 받아 DB에 저장되어 있던 내용을 갱신합니다(파일 업로드 지원).
}
MVCBoardDTO.java
package model2.board;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MVCBoardDTO {
private String idx;
private String name;
private String title;
private String content;
private String postDate;
private String ofile;
private String sfile;
private int downcount;
private String pass;
private int visitcount;
}
페이지 경로를 찾아주는 location.href, history.back() , history.forward() 를 쓰기 위해
JSFunction을 수정했다.
JSFunction.java
package utils;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
public class JSFunction {
// location.href = "페이지 경로"
// history.back() , history.forward()
public static void alertLocation(String msg, String url, JspWriter out) {
try {
String script = ""
+ "<script>"
+ " alert('" + msg + "');"
+ " location.href='" + url + "';"
+ "</script>";
out.print(script);
}catch(Exception e) {
}
}
public static void alertBack(String msg, JspWriter out) {
try {
String script = ""
+ "<script>"
+ " alert('" + msg + "');"
+ " history.back();"
+ "</script>";
out.println(script);
}
catch (Exception e) {}
}
public static void alertLocation(HttpServletResponse resp, String msg, String url) {
// System.out.println("alertLocation()");
try {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
String script = ""
+ "<script>"
+ " alert('" + msg + "');"
+ " location.href='" + url + "';"
+ "</script>";
out.print(script);
}catch(Exception e) {
}
}
public static void alertBack(HttpServletResponse resp,String msg) {
try {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
String script = ""
+ "<script>"
+ " alert('" + msg + "');"
+ " history.back();"
+ "</script>";
out.println(script);
}
catch (Exception e) {}
}
}
이번 정리에서는 구현한 기능들을 이미지로 살펴보며 해당 이미지의 화면이 나오게 하기 위해 어떤 코드를 작성했는지 살펴보려 한다.
1. Index
Index.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<!-- 대문 페이지 -->
<h2>파일 첨부형 게시판</h2>
<a href="../mvcboard/list.do">게시판 목록 바로가기</a>
</body>
</html>
▼ list 화면에서 기능을 수행해주는 ListController.java
package model2.mvcboard;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
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.apache.jasper.runtime.ProtectedFunctionMapper;
import fileupload.MyfileDAO;
import model1.board.BoardDTO;
import model2.board.MVCBoardDAO;
import model2.board.MVCBoardDTO;
import utils.BoardPage;
@WebServlet("/mvcboard/list.do")
public class ListController extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
MVCBoardDAO dao = new MVCBoardDAO();
Map<String , Object> param = new HashMap<>();
String searchField = req.getParameter("searchField");
String searchWord = req.getParameter("searchWord");
if (searchWord != null){
param.put("searchField",searchField);
param.put("searchWord",searchWord);
}
// --------------------- 페이징 ---------------------
int totalCount = dao.selectCount(param); // 게시물 전체 개수
// 어플리케이션 내장객체 ServletContext로 가지고 오기
ServletContext application = getServletContext();
int pageSize = Integer.parseInt(application.getInitParameter("POSTS_PER_PAGE"));
int blockPage = Integer.parseInt(application.getInitParameter("PAGES_PER_BLOCK"));
// 기본적으로 1 페이지에서 시작
int pageNum = 1;
String pageTemp = req.getParameter("pageNum"); // 바뀐 번호를 이용해 페이지 출력
// 페이지 번호를 이용해서 잘라오기, 페이징하기 위한 기준값으로 pagNum 사용
if(pageTemp != null && !pageTemp.equals("")){
pageNum = Integer.parseInt(pageTemp);
}
// (현재페이지 - 1) * POSTS_PER_PAGE + 1
int start = (pageNum - 1) * pageSize + 1;
// 현재페이지 * POSTS_PER_PAGE
int end = pageNum * pageSize;
// Map에 담기
param.put("start",start);
param.put("end",end);
List<MVCBoardDTO> boardLists = dao.selectListPage(param);
dao.close();
// 매핑했던 주소를 넘겨준다. (index.jsp에서 받았던 페이지 주소)
String pagingImg = BoardPage.pagingStr(totalCount, pageSize, blockPage, pageNum, "../mvcboard/list.do");
param.put("pagingImg", pagingImg);
param.put("totalCount", totalCount);
param.put("pageSize", pageSize);
param.put("pageNum", pageNum);
req.setAttribute("boardLists", boardLists);
req.setAttribute("map", param);
// http://localhost:9999/FristJsp
req.getRequestDispatcher("/MVCBoard/List.jsp").forward(req, resp); // 제어권을 넘긴다
}
}
문제)
webapp > MVCBoard > List.jsp 에서 검색하기를 누르면
http://localhost:9999/FristJsp/mvcboard/list.do 로 이동
→ /mvcboard/list.do를 서블릿에서 매핑했기 때문이다!
이게 이렇게 돼야 하는데 지금보니 안된다! 이렇게 될 수 있게 매핑을 해볼 것.
2. List
직접 List.jsp를 실행하면 아무것도 나오지 않는다. → 순수 html 코드만 들어있음.
페이지를 넘겨주기 때문, 컨트롤러로 !
컨트롤러를 거쳐야지만 실행
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>
</head>
<body>
<h2>파일 첨부형 게시판 - 목록 보기(List)</h2>
<!-- 폼태그에 action 속성이 생략되면 현재 페이를 요청한다 (현재 주소창의 URL) -->
<form method="get">
<table border="1" width="90%">
<tr>
<td align="center">
<select name="searchField">
<option value="title">제목</option>
<option value="content">내용</option>
</select>
<input type="text" name="searchWord" />
<input type="submit" value="검색하기" />
</td>
</tr>
</table>
</form>
<table border="1" width="90%">
<tr>
<th width="10%">번호</th>
<th width="*">제목</th>
<th width="15%">작성자</th>
<th width="10%">조회수</th>
<th width="15%">작성일</th>
<th width="8%">첨부</th>
</tr>
<c:choose>
<c:when test="${empty boardLists }">
<tr>
<td colspan="6" align="center">등록된 게시물이 없습니다^^*</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach var="row" items="${boardLists }" varStatus="loop">
<tr>
<td>
<!-- 페이지 단위로 번호 출력하기(버츄얼넘버) -->
${map.totalCount - (((map.pageNum - 1) * map.pageSize) + loop.index) }
</td>
<td>
<a href="../mvcboard/view.do?idx=${row.idx }">${row.title }</a></td>
<td>${row.name }</td>
<td>${row.visitcount }</td>
<td>${row.postDate }</td>
<td>[Down]</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
<table border="1" width="90%">
<tr align="center">
<td>
${map.pagingImg}
</td>
<td align="right">
<button type="button" onclick="location.href='../mvcboard/write.do'">글쓰기</button>
</td>
</tr>
</table>
</body>
</html>
▼ View의 기능을 수행해주는 ViewController.java
package model2.mvcboard;
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 model2.board.MVCBoardDAO;
import model2.board.MVCBoardDTO;
@WebServlet("/mvcboard/view.do")
public class ViewController extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
MVCBoardDAO dao = new MVCBoardDAO();
String idx = req.getParameter("idx");
// 조회수 증가
dao.updateVisitCount(idx);
// 해당글 조회
MVCBoardDTO dto = dao.selectView(idx);
dao.close();
dto.setContent(dto.getContent().replaceAll("\r\n", "<br>"));
req.setAttribute("dto", dto);
req.getRequestDispatcher("/MVCBoard/View.jsp").forward(req, resp);
}
}
3. View
View.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>파일 첨부형 게시판 - 상세보기(View)</h2>
<table border="1" width="90%">
<colgroup>
<col width="15%" />
<col width="35%"/>
<col width="15%"/>
<col width="*%"/>
</colgroup>
<tr>
<td>번호</td>
<td>${dto.idx }</td>
<td>작성자</td>
<td>${dto.name }</td>
</tr>
<tr>
<td>작성일</td>
<td>${dto.postDate }</td>
<td>조회수</td>
<td>${dto.visitcount }</td>
</tr>
<tr>
<td>제목</td>
<td colspan="3">${dto.title }</td>
</tr>
<tr>
<td>내용</td>
<td colspan="3" height="100px">${dto.content }</td>
</tr>
<tr>
<td>첨부파일</td>
<td>
<c:if test="${not empty dto.ofile}">
${dto.ofile }
<a href="../mvcboard/download.do?ofile=${dto.ofile}&sfile=${dto.sfile}&idx=${dto.idx}">[다운로드]</a>
</c:if>
</td>
<td>다운로드수</td>
<td>${dto.downcount}</td>
</tr>
<tr>
<td colspan="4" align="center">
<button type="button" onclick="location.href='../mvcboard/pass.do?mode=edit&idx=${dto.idx}';">수정하기</button>
<button type="button" onclick="location.href='../mvcboard/pass.do?mode=delete&idx=${dto.idx}';">삭제하기</button>
<button type="button" onclick="location.href='../mvcboard/list.do';">목록 바로가기</button>
</td>
</tr>
</table>
</body>
</html>
▼ WriteController.java
글을 쓰고, 파일을 올리는 기능을 처리한다.
package model2.mvcboard;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
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 fileupload.FileUtil;
import model2.board.MVCBoardDAO;
import model2.board.MVCBoardDTO;
import utils.JSFunction;
@WebServlet("/mvcboard/write.do")
public class WriteController extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/MVCBoard/Write.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 어플리케이션 객체 생성
// ServletContext application = getServletContext(); 이렇게 받아와도 된다
String saveDirectory = req.getServletContext().getRealPath("Uploads");
int maxPostSize = 1024 * 1000; //(1MB)
// 객체를 생성해서 업로드하는 부분을 모듈화시킨다
// 클래스 (업로드, 다운로드, 삭제)
// MultipartRequest(request,저장할 경로,파일의최대대크기,인코딩,이름정책)
MultipartRequest mr = FileUtil.uploadFile(req, saveDirectory, maxPostSize);
if (mr == null) {
JSFunction.alertLocation(resp, "첨부 파일이 제한 용량을 초과합니다.", "../mvcboard/write.do");
return;
}
MVCBoardDTO dto = new MVCBoardDTO();
dto.setName(mr.getParameter("name"));
dto.setTitle(mr.getParameter("title"));
dto.setContent(mr.getParameter("content"));
dto.setPass(mr.getParameter("pass"));
String fileName = mr.getFilesystemName("ofile");
if (fileName != null) {
String ext = fileName.substring(fileName.lastIndexOf(".")); // 파일 확장자 .txt
String now = new SimpleDateFormat("yyyyMMdd_HmsS").format(new Date()); // 20240101123456
String newFileName = now + ext; // 20240101123456.txt
File oldFile = new File(saveDirectory + File.separator + fileName);
File newFile = new File(saveDirectory + File.separator + newFileName);
oldFile.renameTo(newFile);
dto.setOfile(fileName);
dto.setSfile(newFileName);
}
// 데이터를 받아 DB에 추가
MVCBoardDAO dao = new MVCBoardDAO();
int result = dao.insertWrite(dto);
dao.close();
if (result > 0) {
resp.sendRedirect("../mvcboard/list.do");
}else {
resp.sendRedirect("../mvcboard/write.do");
}
}
}
4. Write
글쓰기 버튼을 누르면 글을 쓰는 화면이 나오고 글을 쓰고 파일을 올릴 수 있다.
작성자와 제목, 내용과 비밀번호는 필수다. (아직 필수제약 조건을 걸지 않음)
글을 쓰고 작성 완료를 누르면 쓴 글이 목록보기 화면에 올라온 것을 볼 수 있다.
Write.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>
<script>
function validateForm(form){
}
</script>
</head>
<body>
<h2> 파일 첨부형 게시판 - 글쓰기 (Write)</h2>
<form name writefrm method = "post" enctype="multipart/form-data" action ="../mvcboard/write.do" onsubmit="return validateForm(this)">
<table border="1" width="90%">
<tr>
<td>작성자</td>
<td>
<input type="text" name="name" style="width:150px;" />
</td>
</tr>
<tr>
<td>제목</td>
<td>
<input type="text" name="title" style="width:90%;" />
</td>
</tr>
<tr>
<td>내용</td>
<td>
<textarea name="content" style="width:90%;height:100px;"></textarea>
</td>
</tr>
<tr>
<td>첨부 파일</td>
<td>
<input type="file" name="ofile" />
</td>
</tr>
<tr>
<td>비밀번호</td>
<td>
<input type="password" name="pass" style="width:100px;" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">작성 완료</button>
<button type="reset">RESET</button>
<button type="button" onclick="location.href='../mvcboard/list.do';">
목록 바로가기
</button>
</td>
</tr>
</table>
</form>
</body>
</html>
▼ PassController.java
package model2.mvcboard;
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 javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileNameExtensionFilter;
import fileupload.FileUtil;
import model2.board.MVCBoardDAO;
import model2.board.MVCBoardDTO;
import utils.JSFunction;
@WebServlet("/mvcboard/pass.do")
public class PassController extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 비밀번호를 받는 폼을 제공한다
// System.out.println("PassController"); 화면이동이 잘 되는지 보기
// 수정, 삭제를 판단해주는 mode
req.setAttribute("mode", req.getParameter("mode"));
req.getRequestDispatcher("/MVCBoard/Pass.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 받은 비밀번호를 처리한다
String idx = req.getParameter("idx");
String mode = req.getParameter("mode");
String pass = req.getParameter("pass");
MVCBoardDAO dao = new MVCBoardDAO();
// 패스워드 확인
boolean confirmed = dao.confirmPassword(pass, idx);
if (confirmed) {
// 비밀번호 일치해서 삭제한다면
if (mode.equals("delete")) {
dao = new MVCBoardDAO();
MVCBoardDTO dto = dao.selectView(idx);
// 받은 정보를 기반으로 파일 삭제
int result = dao.deletePost(idx);
dao.close();
if (result > 0) {
// 게시물의 파일 삭제하기
String saveFileName = dto.getSfile();
if (saveFileName != null) {
FileUtil.deleteFile(req, "/Uploads", saveFileName);
}
}
JSFunction.alertLocation(resp, "게시글이 삭제되었습니다.", "../mvcboard/list.do");
// 수정하기인지 확인
}else if (mode.equals("edit")){
dao = new MVCBoardDAO();
// 서블릿에서 session 객체 생성하기
HttpSession session = req.getSession();
// 공부를 위해 사용하는 방법, 보안때문에 이렇게 하면 안됨
session.setAttribute(pass, pass);
resp.sendRedirect("../mvcboard/edit.do?idx=" + idx);
}
}else {
// 비밀번호 불일치
JSFunction.alertBack(resp, "비밀번호 검증에 실패했습니다.");
}
}
}
5. Pass.jsp
글을 작성한 사람만 수정, 삭제가 가능하게 하기 위해 비밀번호 확인을 한다.
그리고 비밀번호가 맞으면 수정하기나 글 삭제 페이지로 넘어가고 맞지 않으면 비밀번호 확인에 실패했다는 메세지와 함께 다시 비밀번호 확인 창이 나온다.
Pass.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<script>
function validateForm(form) {
}
</script>
<body>
<form name="writeFrm" method="post" action="../mvcboard/pass.do"
onsubmit="return validateForm(this);">
<!-- 히든폼을 사용하면 직접 값을 받지 않아도 값을 넘길 수 있다 -->
<input type="hidden" name="idx" value="${param.idx }"> <input
type="hidden" name="mode" value="${param.mode }">
<table border="1" width="90%">
<tr>
<td>비밀번호</td>
<td><input type="password" name="pass" style="width: 100px;" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">검증하기</button>
<button type="reset">RESET</button>
<button type="button"
onclick="location.href='../mvcboard/list.do';">목록바로가기</button>
</td>
</tr>
</table>
</form>
</body>
</html>
6. Edit, Delete
비밀번호 확인에 성공하면 수정하기, 글 삭제하기로 넘어간다.
글을 삭제하면 삭제했다는 메세지를 띄운다. (수정하기 기능 구현은 아직 구현되지 않았다.)
Edit.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>파일 첨부형 게시판 - 수정하기(Edit)</h2>
<form>
<table>
<tr>
<td>작성자</td>
<td><input type="text" name="name" style="width: 150px;"
value="${dto.name }" /></td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="name" style="width: 90%;"
value="${dto.title }" /></td>
</tr>
<tr>
<td>내용</td>
<td><textarea name="content" style="width: 90%; height: 100px;"
value="${dto.content }"></textarea></td>
</tr>
<tr>
<td>첨부파일</td>
<td><input type="file" name="ofile" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">작성 완료</button>
<button type="reset">RESET</button>
<button type="button"
onclick="location.href='../mvcboard/list.do';">목록 바로가기</button>
</td>
</tr>
</table>
</form>
</body>
</html>
💡 모든 요청은 컨트롤러를 이용해 처리
get은 뷰 페이지 띄우고 post는 그 뷰를 입력해 처리
윈도우 파일 다운로드 위치)
C:\work\jspworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FristJsp\Uploads
PrintWriter 생성 시 response 의 getWriter()
/mvcboard/view.do
viewController.java
view.jsp 띄우기
'2024_UIUX 국비 TIL' 카테고리의 다른 글
UIUX _국비과정 0708 [이메일 보내기] (0) | 2024.07.23 |
---|---|
UIUX _국비과정 주말공부(0708 모델 2 방식 게시판 수정까지) (2) | 2024.07.22 |
UIUX _국비과정 0703 [서블릿부터 MVC방식까지] (1) | 2024.07.22 |
UIUX _국비과정 0702 [파일 업로드, 다운로드 기능 구현] (0) | 2024.07.19 |
UIUX _국비과정 0701 [모델 2 방식, JSTL] (0) | 2024.07.11 |