미분류

230216

Berylly 2023. 2. 16. 21:03

T.김동식

 

이미지를 첨부한 댓글작성하기

package sec03.brd02;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Date;

public class ArticleVO {
	private int level;
	private int articleNO;
	private int parentNO;
	private String title;
	private String content;
	private String imageFileName;
	private String id;
	private Date writeDate;
	
	public ArticleVO() {
		
	}


	public ArticleVO(int level, int articleNO, int parentNO, String title, String content, String imageFileName,
			String id) {
		super();
		this.level = level;
		this.articleNO = articleNO;
		this.parentNO = parentNO;
		this.title = title;
		this.content = content;
		this.imageFileName = imageFileName;
		this.id = id;
	}




	public int getLevel() {
		return level;
	}


	public void setLevel(int level) {
		this.level = level;
	}


	public int getArticleNO() {
		return articleNO;
	}


	public void setArticleNO(int articleNO) {
		this.articleNO = articleNO;
	}


	public int getParentNO() {
		return parentNO;
	}


	public void setParentNO(int parentNO) {
		this.parentNO = parentNO;
	}


	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 getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		try {
			if(imageFileName!=null && imageFileName.length()!=0) {
				this.imageFileName = URLEncoder.encode(imageFileName, "UTF-8");  //파일이름에 특수문자가 있을 경우 인코딩합니다.
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public Date getWriteDate() {
		return writeDate;
	}


	public void setWriteDate(Date writeDate) {
		this.writeDate = writeDate;
	}
	
	
	
	
	

}
package sec03.brd02;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BoardDAO {
	private DataSource dataFactory;//데이터 연결을 위한 팩토리
	Connection conn;//데이터베이스와의 연결
	PreparedStatement pstmt;//미리컴파일, 개체에 저장되 여러번 효율적으로 실행

	public BoardDAO() {
		try {
			Context ctx = new InitialContext();//초기 컨덱스트 구성
			
			//lookup 검색할 개체의 이름검색
			Context envContext = (Context) ctx.lookup("java:/comp/env");
			dataFactory = (DataSource) envContext.lookup("jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<ArticleVO> selectAllArticles() {
		List<ArticleVO> articlesList = new ArrayList<ArticleVO>();
		
		try {
			//dataFactory가 나타내는 데이터와 연결
			conn = dataFactory.getConnection();
			
			//sql문 매개 변수화
			String query = "SELECT LEVEL,articleNO,parentNO,title,content,id,writeDate" + " from t_board"
					+ " START WITH  parentNO=0" + " CONNECT BY PRIOR articleNO=parentNO"
					+ " ORDER SIBLINGS BY articleNO DESC";
			System.out.println(query);
			
			//prepareStatement 매개변수화된 sql문을 데이터베이스로 보내기전 준비된 개체로 만듦
			pstmt = conn.prepareStatement(query);
			
			//ResultSet 데이터베이스 결과 집합을 나타내는 데이터 테이블
			//execute(실행하다), pstmt쿼리를 실행 후 개체 반환
			ResultSet rs = pstmt.executeQuery();
			
			while (rs.next()) {
				int level = rs.getInt("level");
				int articleNO = rs.getInt("articleNO");
				int parentNO = rs.getInt("parentNO");
				String title = rs.getString("title");
				String content = rs.getString("content");
				String id = rs.getString("id");
				Date writeDate = rs.getDate("writeDate");
				
				//article 객체 만들기
				ArticleVO article = new ArticleVO();
				article.setLevel(level);
				article.setArticleNO(articleNO);
				article.setParentNO(parentNO);
				article.setTitle(title);
				article.setContent(content);
				article.setId(id);
				article.setWriteDate(writeDate);
				
				//만든객체 articlesList에 추가하기
				articlesList.add(article);
			}
			
			rs.close();//데이터 테이블 닫기
			pstmt.close();//sql문개체 닫기
			conn.close();//데이터와 연결 닫기
			
		} catch (Exception e) {e.printStackTrace();}
		return articlesList;//articlesList 반환
	}

	
	private int getNewArticleNO() {
		try {
			//dataFactory가 나타내는 데이터와 연결
			conn = dataFactory.getConnection();
			
			//sql문 매개 변수화
			//articleNO의 max값 구해
			String query = "SELECT  max(articleNO) from t_board ";
			System.out.println(query);
			
			//prepareStatement 매개변수화된 sql문을 데이터베이스로 보내기전 준비된 개체로 만듦
			pstmt = conn.prepareStatement(query);
			
			//ResultSet 데이터베이스 결과 집합을 나타내는 데이터 테이블
			//execute(실행하다), pstmt쿼리를 실행 후 개체 반환
			ResultSet rs = pstmt.executeQuery(query);
			
			//다음객체가 있다면
			if (rs.next())
				//이 ResultSet 개체의 현재 행에 있는 지정된 열의 값을 int로 검색
				return (rs.getInt(1) + 1);//+1
			
			rs.close();//데이터 테이블 닫기
			pstmt.close();//sql문개체 닫기
			conn.close();//데이터와 연결 닫기
		
		} catch (Exception e) {e.printStackTrace();}
		
		return 0;//다음객체가 없다면 변화없음.
	}

	public void insertNewArticle(ArticleVO article) {
		try {
			//dataFactory가 나타내는 데이터와 연결
			conn = dataFactory.getConnection();
			
			int articleNO = getNewArticleNO();
			int parentNO = article.getParentNO();
			String title = article.getTitle();
			String content = article.getContent();
			String id = article.getId();
			String imageFileName = article.getImageFileName();
			
			//sql문 매개 변수화
			String query = "INSERT INTO t_board (articleNO, parentNO, title, content, imageFileName, id)"
					+ " VALUES (?, ? ,?, ?, ?, ?)";
			System.out.println(query);
			
			//prepareStatement 매개변수화된 sql문을 데이터베이스로 보내기전 준비된 개체로 만듦
			pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, articleNO);
			pstmt.setInt(2, parentNO);
			pstmt.setString(3, title);
			pstmt.setString(4, content);
			pstmt.setString(5, imageFileName);
			pstmt.setString(6, id);
			
			//execute(실행하다)
			//executeUpdate 업데이트, 수정, 삭제 등 수행
			pstmt.executeUpdate();
			
			pstmt.close();//sql문개체 닫기
			conn.close();//데이터와 연결 닫기
			
		} catch (Exception e) {e.printStackTrace();}
	}

}
package sec03.brd02;

import java.util.List;

public class BoardService {
	BoardDAO boardDAO;
	public BoardService() {
		boardDAO = new BoardDAO();
	}

	public List<ArticleVO> listArticles() {
		List<ArticleVO> articlesList = boardDAO.selectAllArticles();
		return articlesList;
	}
	
	public void addArticle(ArticleVO article){
		boardDAO.insertNewArticle(article);		
	}

}
package sec03.brd02;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
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.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@WebServlet("/board/*")
public class BoardController extends HttpServlet {
	private static String ARTICLE_IMAGE_REPO = "C:\\board\\article_image";
	BoardService boardService;
	ArticleVO articleVO;

	public void init(ServletConfig config) throws ServletException {
		boardService = new BoardService();
		articleVO = new ArticleVO();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doHandle(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
		doHandle(request, response);
	}

	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nextPage = "";
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		//url 정보를 불러와 action에 저장한다.
		String action = request.getPathInfo();System.out.println("action:" + action);
		
		try {
			List<ArticleVO> articlesList = new ArrayList<ArticleVO>();
			
			//url 정보가 null일 경우
			if (action == null) {
				articlesList = boardService.listArticles();
				request.setAttribute("articlesList", articlesList);//속성에 객체 저장
				nextPage = "/board02/listArticles.jsp";//리스트페이지로 이동
				
			} else if (action.equals("/listArticles.do")) {
				articlesList = boardService.listArticles();
				request.setAttribute("articlesList", articlesList);
				nextPage = "/board02/listArticles.jsp";//리스트페이지로 이동
				
			} else if (action.equals("/articleForm.do")) {
				nextPage = "/board02/articleForm.jsp";//리스트페이지로 이동
				
			//url 정보가 addArticle.do일 경우
			} else if (action.equals("/addArticle.do")) {
				//upload() 메서드를 수행한 뒤 Map 키에 값을 매칭하는 개체 articleMap 생성
				Map<String, String> articleMap = upload(request, response);
				String title = articleMap.get("title");
				String content = articleMap.get("content");
				String imageFileName = articleMap.get("imageFileName");

				articleVO.setParentNO(0);
				articleVO.setId("hong");
				articleVO.setTitle(title);
				articleVO.setContent(content);
				articleVO.setImageFileName(imageFileName);
				boardService.addArticle(articleVO);
				nextPage = "/board/listArticles.do";
			}else {
				nextPage = "/board02/listArticles.jsp";
			}

			RequestDispatcher dispatch = request.getRequestDispatcher(nextPage);
			dispatch.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//upload() 메서드
	private Map<String, String> upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Map, key value로 데이터를 저장하는데 사용되는 인터페이스, 
		//HashMap은 Interface 를 Implements 한 클래스
		Map<String, String> articleMap = new HashMap<String, String>();
		
		String encoding = "utf-8";
		
		//C:\\board\\article_image
		//지정된 문자열 경로로 새파일 인스턴스 생성
		File currentDirPath = new File(ARTICLE_IMAGE_REPO);
		
		//파일오브젝트를 생성하는 클래스, 메모리/데이터처리에 관한 메서드등이 담겨있다.
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(currentDirPath);//경로지정
		factory.setSizeThreshold(1024 * 1024);//크기제한
		
		//업로드 요청을 처리하는 ServletFileUpload
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
			//요청을 파싱해 List items을 구함.
			List items = upload.parseRequest(request);
			
			for (int i = 0; i < items.size(); i++) {
				FileItem fileItem = (FileItem) items.get(i);//인덱싱에 해당되는 파일을 받아
				
				if (fileItem.isFormField()) {//FormField 일때
					System.out.println(fileItem.getFieldName() + "=" + fileItem.getString(encoding));
					
					//upload() 메서드를 수행한 뒤 Map 키에 값을 매칭하는 개체 articleMap 생성
					//Map<String, String> articleMap = upload(request, response);
					//위에서 생성한 articleMap에 key와 value를 배치
					articleMap.put(fileItem.getFieldName(), fileItem.getString(encoding));
					
				} else {//FormField가 아닐경우
					System.out.println("파라미터명:" + fileItem.getFieldName());
					System.out.println("파일크기:" + fileItem.getSize() + "bytes");
					
					//필요없는 경우도 있으나, 있어야 하는 파일절차
					if (fileItem.getSize() > 0) {
						int idx = fileItem.getName().lastIndexOf("\\");//윈도우기반
						if (idx == -1) {
							idx = fileItem.getName().lastIndexOf("/");//리눅스기반
						}
						
						//순수한 파일명 추출
						String fileName = fileItem.getName().substring(idx + 1);
						System.out.println("파일명:" + fileName);
					//필요없는 경우도 있으나, 있어야 하는 파일절차
						
						//upload() 메서드를 수행한 뒤 Map 키에 값을 매칭하는 개체 articleMap 생성
						//Map<String, String> articleMap = upload(request, response);
						//위에서 생성한 articleMap에 key와 value를 배치
						//익스플로러에서 업로드 파일의 경로 제거 후 map에 파일명 저장
						articleMap.put(fileItem.getFieldName(), fileName);  
						
						//factory.setRepository(currentDirPath);
						//경로지정한 곳에 uploadFile 객체 생성+업로드
						File uploadFile = new File(currentDirPath + "\\" + fileName);
						fileItem.write(uploadFile);

					} 
				}
			} 
		} catch (Exception e) {e.printStackTrace();}

		//Map<String, String> articleMap 리턴
		return articleMap;
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<%
  request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<style>
.cls1 {
	text-decoration: none;
}

.cls2 {
	text-align: center;
	font-size: 30px;
}
</style>
<meta charset="UTF-8">
<title>글목록창</title>
</head>
<body>

	<table align="center" border="1" width="80%">
		<tr height="10" align="center" bgcolor="lightgreen">
			<td>글번호</td>
			<td>작성자</td>
			<td>제목</td>
			<td>작성일</td>
		</tr>
		
		<c:choose>
			<c:when test="${empty articlesList }">
				<tr height="10">
					<td colspan="4">
						<p align="center">
							<b><span style="font-size: 9pt;">등록된 글이 없습니다.</span></b>
						</p>
					</td>
				</tr>
			</c:when>

			<c:when test="${!empty  articlesList}">
				<c:forEach var="article" items="${articlesList }"
					varStatus="articleNum">
					<tr align="center">
						<td width="5%">${articleNum.count}</td>
						<td width="10%">${article.id }</td>
						<td align='left' width="35%"><span
							style="padding-right: 30px"></span> <c:choose>
							
							
								<c:when test='${article.level > 1 }'>
									<c:forEach begin="1" end="${article.level }" step="1">
										<span style="padding-left: 10px"></span>
									</c:forEach>
									<span style="font-size: 12px;">[답변]</span>
									<a class='cls1'
										href="${contextPath}/board/viewArticle.do?articleNO=${article.articleNO}">${article.title}</a>
								</c:when>
								
								
								<c:otherwise>
									<a class='cls1'
										href="${contextPath}/board/viewArticle.do?articleNO=${article.articleNO}">${article.title }</a>
								</c:otherwise>
								
								
							</c:choose></td>
						<td width="10%"><fmt:formatDate value="${article.writeDate}" /></td>
					</tr>
				</c:forEach>
			</c:when>


		</c:choose>
	</table>
	<a class="cls1" href="${contextPath}/board/articleForm.do"><p
			class="cls2">글쓰기</p></a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
  request.setCharacterEncoding("UTF-8");
%> 
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  /> 
<head>
<meta charset="UTF-8">
<title>글쓰기창</title>
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">

	/* url을 읽어 이미지를 #preview에 띄움 */

   function readURL(input) {
      if (input.files && input.files[0]) {
	      var reader = new FileReader();
	      reader.onload = function (e) {
	        $('#preview').attr('src', e.target.result);
          }
         reader.readAsDataURL(input.files[0]);
      }
  }  
  function backToList(obj){
    obj.action="${contextPath}/board/listArticles.do";
    obj.submit();
  }

</script>
 <title>새글 쓰기 창</title>
</head>
<body>
<h1 style="text-align:center">새글 쓰기</h1>
  <form name="articleForm" method="post"   action="${contextPath}/board/addArticle.do"   enctype="multipart/form-data">
    <table border=0 align="center">
     <tr>
	   <td align="right">글제목: </td>
	   <td colspan="2"><input type="text" size="67"  maxlength="500" name="title" /></td>
	 </tr>
	 <tr>
		<td align="right" valign="top"><br>글내용: </td>
		<td colspan=2><textarea name="content" rows="10" cols="65" maxlength="4000"></textarea> </td>
     </tr>
     <tr>
        <td align="right">이미지파일 첨부:  </td>
	     <td> <input type="file" name="imageFileName" onchange="readURL(this);" /></td>
         <td><img  id="preview" src="#"   width=200 height=200/></td>
	 </tr>
	 <tr>
	    <td align="right"> </td>
	    <td colspan="2">
	       <input type="submit" value="글쓰기" />
	       <input type=button value="목록보기"onClick="backToList(this.form)" />
	    </td>
     </tr>
    </table>
  </form>
</body>
</html>

 

 

 

업로드 완료후 alert창을 추가하고

업로드 받은 이미지를 자동 폴더정리 구현하기

package sec03.brd03;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
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.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

@WebServlet("/board/*")
public class BoardController extends HttpServlet {
	private static String ARTICLE_IMAGE_REPO = "C:\\board\\article_image";
	BoardService boardService;
	ArticleVO articleVO;

	
	public void init(ServletConfig config) throws ServletException {
		boardService = new BoardService();
		articleVO = new ArticleVO();
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doHandle(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
		doHandle(request, response);
	}

	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nextPage = "";
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		String action = request.getPathInfo();
		System.out.println("action:" + action);
		try {
			List<ArticleVO> articlesList = new ArrayList<ArticleVO>();
			if (action == null) {
				articlesList = boardService.listArticles();
				request.setAttribute("articlesList", articlesList);
				nextPage = "/board02/listArticles.jsp";
			} else if (action.equals("/listArticles.do")) {
				articlesList = boardService.listArticles();
				request.setAttribute("articlesList", articlesList);
				nextPage = "/board02/listArticles.jsp";
			} else if (action.equals("/articleForm.do")) {
				nextPage = "/board02/articleForm.jsp";
			} else if (action.equals("/addArticle.do")) {
				int articleNO=0;
				Map<String, String> articleMap = upload(request, response);
				String title = articleMap.get("title");
				String content = articleMap.get("content");
				String imageFileName = articleMap.get("imageFileName");
				
				articleVO.setParentNO(0);
				articleVO.setId("hong");
				articleVO.setTitle(title);
				articleVO.setContent(content);
				articleVO.setImageFileName(imageFileName);
				
				articleNO= boardService.addArticle(articleVO);
				
				//imageFileName 이름이 있을때
				if(imageFileName!=null && imageFileName.length()!=0) {
					//1. 지정한 경로 ARTICLE_IMAGE_REPO/temp폴더 안에 imageFileName인 파일 객체
				    File srcFile = new 	File(ARTICLE_IMAGE_REPO +"\\"+"temp"+"\\"+imageFileName);
				    //2. 지정한 경로 ARTICLE_IMAGE_REPO/articleNO안 객체
					File destDir = new File(ARTICLE_IMAGE_REPO +"\\"+articleNO);
					
					//2 정보로 mkdirs
					destDir.mkdirs();
					
					//moveFile()는 인자로 전달되는 Path로 파일을 이동
					//moveFileToDirectory createDestDir 값 true, false 
					//false 존재하지 않는 폴더는 생성하지 않는다.
					//true 존재하지 않는 폴더를 생성해줌.
					//srcFile 이미지를 destDir로 moveFileToDirectory한다.
					FileUtils.moveFileToDirectory(srcFile, destDir, true);
				}
				
				PrintWriter pw = response.getWriter();
				pw.print("<script>" 
						 //안내 alert
				         +"  alert('새글을 추가했습니다.');" 
				         //사용자가 alert를 확인하면 listArticles.do로 location.href
						 +" location.href='"+request.getContextPath()+"/board/listArticles.do';"
				         +"</script>");

				return;
			}else {
				nextPage = "/board02/listArticles.jsp";
			}

			RequestDispatcher dispatch = request.getRequestDispatcher(nextPage);
			dispatch.forward(request, response);
			
		} catch (Exception e) {e.printStackTrace();}
	}

	private Map<String, String> upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> articleMap = new HashMap<String, String>();
		String encoding = "utf-8";
		File currentDirPath = new File(ARTICLE_IMAGE_REPO);
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(currentDirPath);
		factory.setSizeThreshold(1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			for (int i = 0; i < items.size(); i++) {
				FileItem fileItem = (FileItem) items.get(i);
				if (fileItem.isFormField()) {
					System.out.println(fileItem.getFieldName() + "=" + fileItem.getString(encoding));
					articleMap.put(fileItem.getFieldName(), fileItem.getString(encoding));
				} else {
					System.out.println("파라미터명:" + fileItem.getFieldName());
					System.out.println("파일크기:" + fileItem.getSize() + "bytes");
					if (fileItem.getSize() > 0) {
						int idx = fileItem.getName().lastIndexOf("\\");
						if (idx == -1) {
							idx = fileItem.getName().lastIndexOf("/");
						}

						String fileName = fileItem.getName().substring(idx + 1);
						System.out.println("파일명:" + fileName);
						articleMap.put(fileItem.getFieldName(), fileName); 
						File uploadFile = new File(currentDirPath + "\\temp\\" + fileName);
						fileItem.write(uploadFile);

					}
				} 
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return articleMap;
	}

}