무작정 개발.Vlog

[Servlet] - 이미지 게시판 만들기

by 무작정 개발
반응형
2022.02.24(44일 차)

 

이번에는 Servlet으로 이미지 게시판을 만드는 것을 정리할 예정이다.

 

 

DB 테이블 생성

 

imagetest 테이블 생성
imagetest 테이블 생성

 

 

DTO, DAO 클래스 생성하기

 

ImageTestDTO 

package com.imageTest;

public class ImageTestDTO {
	
	
	private int num;
	private String subject;
	private String saveFileName;
    
    //getter/setter 생성
    
 }

 

ImageTestDAO

package com.imageTest;

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

public class ImageTestDAO {

	private Connection conn = null;

	public ImageTestDAO(Connection conn) {

		this.conn = conn;
	}

	// 레코드 번호
	public int getMaxNum() {

		int maxNum = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql;

		try {

			sql = "select nvl(max(num),0) from imageTest";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				maxNum = rs.getInt(1);
			}

			rs.close();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}

		return maxNum;

	}

	// 파일 데이터 입 력
	public void insertData(ImageTestDTO dto) {

		PreparedStatement pstmt = null;
		String sql;

		try {

			sql = "insert into imageTest (num,subject,saveFileName) ";
			sql += "values (?,?,?)";

			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, dto.getNum());
			pstmt.setString(2, dto.getSubject());
			pstmt.setString(3, dto.getSaveFileName());

			pstmt.executeUpdate();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

	// 파일데이터 전체조회
	public List<ImageTestDTO> getList(int start, int end) {

		List<ImageTestDTO> lists = new ArrayList<ImageTestDTO>();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql;

		try {
			sql = "select * from (select rownum rnum,num,subject,saveFileName ";
			sql += "from imageTest order by num desc) ";
			sql += "where rnum >= ? and rnum <=? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, start);
			pstmt.setInt(2, end);

			rs = pstmt.executeQuery();

			while (rs.next()) {
				ImageTestDTO dto = new ImageTestDTO();
				dto.setNum(rs.getInt("num"));
				dto.setSubject(rs.getString("subject"));
				dto.setSaveFileName(rs.getString("saveFileName"));
				lists.add(dto);
			}
			rs.close();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return lists;
	}

	// 특정 데이터 조회
	public ImageTestDTO getReadData(int num) {

		ImageTestDTO dto = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql;

		try {

			sql = "select num,subject,saveFileName from imageTest where num = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, num); // 매개변수로 받은 num. where조건에 넣어줌
			rs = pstmt.executeQuery();

			if (rs.next()) {
				dto = new ImageTestDTO();
				dto.setNum(rs.getInt("num"));
				dto.setSubject(rs.getString("subject"));
				dto.setSaveFileName(rs.getString("saveFileName"));
			}
			rs.close();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return dto;

	}

	// 파일데이터 삭제
	public void deleteData(int num) {

		PreparedStatement pstmt = null;
		String sql;
		try {
			sql = "delete imageTest where num=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	// 데이터 세기
	public int getDataCount() {

		int totalDataCount = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql;
		try {
			sql = "select nvl(count(*),0) from imageTest ";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next())
				totalDataCount = rs.getInt(1);

			rs.close();
			pstmt.close();

		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return totalDataCount;
	}

}

 

 

Servlet 클래스 생성하기

 

package com.imageTest;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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 com.util.DBConn;
import com.util.FileManager;
import com.util.MyUtil;

public class ImageTestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void forward(HttpServletRequest req, HttpServletResponse resp,
			String url) throws ServletException, IOException {
		RequestDispatcher rd = req.getRequestDispatcher(url);
		rd.forward(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Connection conn = DBConn.getConnection();
		ImageTestDAO dao = new ImageTestDAO(conn);
		// 페이징
		MyUtil myUtil = new MyUtil();
		String cp = req.getContextPath();
		String uri = req.getRequestURI();
		String url;
		// 파일 업로드 위치 지정
		String root = getServletContext().getRealPath("/");
		String path = root + File.separator + "pds" + File.separator
				+ "imageFile";
		File f = new File(path);

		if (!f.exists()) {
			f.mkdirs();
		}

		if (uri.indexOf("write.do") != -1) {
			url = "/imageTest/write.jsp";
			forward(req, resp, url);

		} else if (uri.indexOf("write_ok.do") != -1) {

			String encType = "UTF-8";
			
			int maxSize = 10 * 1024 * 1024;
			// 파일 업로드
			MultipartRequest mr = new MultipartRequest(req, path, maxSize,
					encType, new DefaultFileRenamePolicy());

			// DB에 파일정보 입력
			// 업로드한 파일로부터 정보 추출
			if (mr.getFile("uploadFile") != null) {// null이 아니면 파일이 제대로 업로드된것
				ImageTestDTO dto = new ImageTestDTO();
				int maxNum = dao.getMaxNum();
				dto.setNum(maxNum + 1);
				dto.setSubject(mr.getParameter("subject"));
				dto.setSaveFileName(mr.getFilesystemName("uploadFile"));
				dao.insertData(dto);
			}

			// list.do 페이지로 리다이렉트
			url = cp + "/image/list.do";
			resp.sendRedirect(url);

		} else if (uri.indexOf("list.do") != -1) {

			String pageNum = req.getParameter("pageNum");
			int currentPage = 1; // 처음 띄우는 리스트 페이지

			if (pageNum != null) {
				currentPage = Integer.parseInt(pageNum);
			}

			int dataCount = dao.getDataCount();
			int numPerPage = 9;
			int totalPage = myUtil.getPageCount(numPerPage, dataCount);

			if (currentPage > totalPage)
				currentPage = totalPage;

			int start = (currentPage - 1) * numPerPage + 1;
			int end = currentPage * numPerPage;

			String listUrl = cp + "/image/list.do";
			List<ImageTestDTO> lists = dao.getList(start, end);
			String pageIndexList = myUtil.pageIndexList(currentPage, totalPage,
					listUrl);

			// 삭제경로
			String deletePath = cp + "/image/delete.do";
			// 이미지파일경로
			String imagePath = cp + "/pds/imageFile";
			req.setAttribute("imagePath", imagePath);
			
			int totalArticle = dao.getDataCount();

			// 파일정보 테이블을 리스트로 전달
			req.setAttribute("lists", lists);
			req.setAttribute("pageNum", pageNum);
			req.setAttribute("currentPage", currentPage);
			req.setAttribute("deletePath", deletePath);
			req.setAttribute("pageIndexList", pageIndexList);
			req.setAttribute("totalArticle", totalArticle);
			req.setAttribute("totalPage", totalPage);
			
			// list.jsp 페이지로 포워드
			url = "/imageTest/list.jsp";
			forward(req, resp, url);

		} else if (uri.indexOf("delete.do") != -1) {

			int num = Integer.parseInt(req.getParameter("num"));
			int pageNum = Integer.parseInt(req.getParameter("pageNum"));
			//int currentPage = Integer.parseInt(req.getParameter("currentPage"));
			
			ImageTestDTO dto = dao.getReadData(num);

			// 물리적 파일 삭제
			FileManager.doFileDelete(dto.getSaveFileName(), path);

			// 테이블 정보 삭제
			dao.deleteData(num);

			// 삭제 진행 후 리스트 페이지로 리다이렉트
			url = cp + "/image/list.do?pageNum=" + pageNum;
			resp.sendRedirect(url);
		}
	}
}

 

 

web.xml 매핑 정보 등록하기

<!-- 이미지 게시판 -->
   <servlet>
 	<servlet-name>imageServlet</servlet-name>
  	<servlet-class>com.imageTest.ImageTestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>imageServlet</servlet-name>
  	<url-pattern>/image/*</url-pattern>
  </servlet-mapping>

 

 

JSP 페이지 생성하기

 

write.jsp - (이미지 업로드 페이지)

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>이미지 등록</title>

<link rel="stylesheet" href="<%=cp %>/imageTest/css/style.css" type="text/css" />
<script type="text/javascript" src="<%=cp%>/imageTest/data/image.js"></script>
<script type="text/javascript">
	function sendIt() {
		
	    f = document.myForm;
	    
	    str = f.subject.value;
	    str = str.trim();
	    if(!str) {
	        alert("제목을 입력하세요 !!!");
	        f.subject.focus();
	        return;
	    }
	    f.subject.value = str;
	
	    str = f.uploadFile.value;
	    if(!str) {
	        alert("이미지 파일을 선택 하세요 !!!");
	        f.uploadFile.focus();
	        return;
	    }
	    
	    f.action="/study/image/write_ok.do";
	    f.submit();
	}
</script>
</head>
<body>
<br/><br/>
<table width="600" border="2" cellpadding="0" cellspacing="0"
bordercolor="#d6d4a6" align="center">

<tr height="40">
   <td style="padding-left: 20px;">
   <b>이미지 게시판</b>
   </td>
</tr>   
</table>

<form action="<%=cp%>/image/write_ok.do" method="post" enctype="multipart/form-data">
<table width="600" border="0" cellspacing="0" align="center">
<tr><td colspan="2" height="1" bgcolor="#dbdbdb" align="center"></td></tr>   
   <tr>
      <td width="140" height="30" bgcolor="#eeeeee" style="padding-left: 20px;">
      제&nbsp;&nbsp;&nbsp;목
      </td>
      <td width="460" style="padding-left: 10px;">
      <input type="text" name="subject" size="35" maxlength="20" class="boxTF"/>
      </td>
   </tr>
   
   <tr><td colspan="2" height="1" bgcolor="#dbdbdb" align="center"></td></tr>   
   
   <tr>
      <td width="140" height="30" bgcolor="#eeeeee" style="padding-left: 20px;">
      파&nbsp;&nbsp;&nbsp;일
      </td>
      <td width="460" style="padding-left: 10px;">
      <input type="file" name="upload" maxlength="100" size="48" class="boxTF"/>
      </td>
   </tr>      
   
   <tr><td colspan="2" height="3" bgcolor="#dbdbdb" align="center"></td></tr>   
   </table>

   <table width="600" border="0" cellpadding="0" cellspacing="3" align="center">
   <tr align="center">
      <td height="40">
      <!-- mailSend(); -> mail.js에 있다. -->
      <input type="submit" value="등록하기" class="btn2"/>   
      <input type="reset" value="다시입력" class="btn2"
      onclick="document.myForm.senderName.focus();"/>
      <input type="reset" value="작성취소" class="btn2"
      onclick="javascript:location.href='<%=cp%>/image/list.do';">

</table>
</form>

</body>
</html>

 

list.jsp - (이미지 조회 페이지)

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>이미지 게시판</title>
<link rel="stylesheet" href="<%=cp %>/imageTest/css/style.css" type="text/css" />
<link rel="stylesheet" href="<%=cp %>/imageTest/css/list.css" type="text/css" />

</head>
<body>
<br/><br/>
<table width="600" border="2" cellpadding="0" cellspacing="0"
bordercolor="#d6d4a6" align="center">

<tr height="40">
   <td style="padding-left: 20px;">
   <b>이미지 게시판</b>
   </td>
</tr>   
</table>
<br/><br/>

<table width="600" align="center" style="font-family: 돋움; font-size: 10pt;" cellspacing="2" cellpadding="1" >

<tr>
	<td align="left" colspan="2" width="400">
	Total ${totalArticle } articles, ${totalPage } pages / Now Page is ${currentPage }
	</td>
	<td align="right" colspan="1" width="200">
	<input type="button" value="게시물등록" onclick="javascript:location='<%=cp%>/image/write.do';"/>
	</td>
</tr>
<tr><td style="border-bottom:2px solid #DBDBDB;" colspan="3"></td></tr>
<% 
	int newLine = 0; 
	int articleCount=0;
	int cnt = 0;
%>
	<c:forEach var="dto"
	
	+ items="${lists }">
<% 
	if(newLine==0){
		out.print("<tr>");
	}
	newLine++;
	articleCount++;
%>
	<td align="center" width="190">
		<input type="hidden" value="${dto.num }" name="num" />
		<a href="${imagePath }/${dto.saveFileName }">
			<img alt="" src="${imagePath }/${dto.saveFileName }" width="190" height="190">
			<br>${dto.subject }
		</a><a href="${deletePath}?num=${dto.num }&pageNum=${pageNum }">삭제</a>
	</td>
<% 
	if(newLine==3){	
		out.print("</tr>");
		newLine = 0;
	}
%>
	</c:forEach>
<%
	while(newLine>0&&newLine<2){
		out.print("<td width='180'></td>");
		newLine++;
	}
	out.print("</tr>");
%>

<tr><td style="border-bottom:2px solid #DBDBDB;" colspan="3"></td></tr>	
<tr>
	<td align="center" colspan="3">
	<c:if test="${dataCount!=0 }">
		${pageIndexList }
	</c:if>
	<c:if test="${dataCount==0 }">
		등록된 파일이 없습니다
	</c:if>
	</td>
</tr>

</table>
<br/><br/>

</body>
</html>
반응형

블로그의 정보

무작정 개발

무작정 개발

활동하기