Dev/Struts

Struts1/iBatis - 이미지 게시판 만들기

창문닦이 2019. 3. 24. 22:07

1. 데이터베이스에 테이블 생성

CREATE TABLE imagetest

(NUM NUMBER(7) PRIMARY KEY,

SUBJECT VARCHAR2(50) NOT NULL,

SAVEFILENAME VARCHAR2(50),

ORIGINALFILENAME VARCHAR2(50))

2. sqlMapConfig.xml 등록

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMapConfig

PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<!-- Config(환경설정파일) -->

<sqlMapConfig>

<settings

cacheModelsEnabled="false"

useStatementNamespaces="true"/>

<!-- DB연결자. JDBC등록된 내용도 있고 이 내용도 함께 존재해야함 -->

<transactionManager type="JDBC" commitRequired="false">

<dataSource type="SIMPLE">

<property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>

<property name="JDBC.ConnectionURL"

value="jdbc:oracle:thin:@localhost:1521:xe"/>

<property name="JDBC.Username" value="suzi"/>

<property name="JDBC.Password" value="a123"/>

</dataSource>

</transactionManager>

<!-- 이 sqlMap은 struts에서 struts-config_temp.xml를 만들어두고 복사해서 사용한것과 동일 -->

<sqlMap resource="com/util/sqlMap/boardTest_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/fileTest_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/member_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/image_sqlMap.xml"/>

</sqlMapConfig>

3. image-sqlMap.xml 등록

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMap

PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<!-- Mapper -->

<sqlMap namespace="img">

<select id="maxNum" resultClass="Integer">

select nvl(max(num),0) from imageTest

</select>

<!-- 컬럼명이 데이터베이스에 있는 컬럼명과 dto 클래스에 있는 변수명과 상이할 경우

parameterMap="" 속성을 사용한다. 실제로는 많이 사용하지 않음 -->

<insert id="insertData" parameterClass="com.imageTest.ImageForm" >

insert into imageTest (num,subject,saveFileName,originalFileName)

values (#num#,#subject#,#saveFileName#,#originalFileName#)

</insert>

<!-- 페이징 작업을 위해 where조건 반영 -->

<select id="listData" resultClass="com.imageTest.ImageForm" parameterClass="map">

<![CDATA[

select * from(

select rownum rnum, data.* from(

select num,subject,saveFileName,originalFileName

from imageTest order by num desc) data)

where rnum>=#start# and rnum<=#end#

]]>

</select>

<!-- 다운로드시 -->

<select id="readData" resultClass="com.imageTest.ImageForm"

parameterClass="int">

select num,subject,saveFileName,originalFileName

from imageTest where num=#num#

</select>

<!-- 게시물 카운팅 -->

<select id="dataCount" resultClass="int">

select nvl(count(num),0) from imageTest

</select>

<!-- 삭제 -->

<delete id="deleteData" parameterClass="int">

delete imageTest where num=#num#

</delete>

</sqlMap>

4. web.xml 등록

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>

/WEB-INF/struts-config.xml,

/WEB-INF/struts-config_test.xml,

/WEB-INF/struts-config_board.xml,

/WEB-INF/struts-config_boardTest.xml,

/WEB-INF/struts-config_fileTest.xml,

/WEB-INF/struts-config_member.xml,

/WEB-INF/struts-config_image.xml

</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

 <servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

5. struts-config_image.xml 생성

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

"http://struts.apache.org/dtds/struts-config_1_3.dtd">

       

<struts-config>

<form-beans>

<form-bean name="ImageForm" type="com.imageTest.ImageForm"/>

</form-beans>

<action-mappings>

<action path="/img" type="com.imageTest.ImageAction"

name="ImageForm" scope="request" parameter="method">

<forward name="write" path="/imageTest/write.jsp"/>

<forward name="write_ok" redirect="true" path="/img.do?method=list"/>

<forward name="list" path="/imageTest/list.jsp"/>

<forward name="delete" redirect="true" path="/img.do?method=list"/>

</action>

</action-mappings>

</struts-config>   

6. DTO 생성

package com.imageTest;

import org.apache.struts.action.ActionForm;

import org.apache.struts.upload.FormFile;

public class ImageForm extends ActionForm{

private static final long serialVersionUID = 1L;

private int num;

private String subject;

private String saveFileName;

private String originalFileName;

//아파치에서 제공하는 파일 업로드시 사용하는 클래스

//jsp페이지에서의 input 데이터의 name과 반드시 일치해야 한다.

//파일을 2개 이상 올릴 경우 배열로 처리해서 진행하면 된다.

private FormFile upload;

//일렬번호 재정렬. 중간에 있는 파일이 삭제되더라도 일련번호가 정렬되도록

private int listNum;

//파일의 다운로드 경로

private String urlFile;

Getter, Setter 생성

}

7. Action 클래스 생성

public class ImageAction extends DispatchAction{

//이미지 등록 페이지

public ActionForward write(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

return mapping.findForward("write");

}

//파일 업로드 등록

public ActionForward write_ok(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

HttpSession session = request.getSession();

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" +  File.separator + "imageFile";

ImageForm f = (ImageForm)form;

//파일 업로드

String newFileName = FileManager.doFileUpload(f.getUpload(), savePath);

//파일에 대한 정보 추출후 DB반영

if(newFileName!=null){

int maxNum = dao.getIntValue("img.maxNum");

f.setNum(maxNum+1);

f.setSaveFileName(newFileName);

f.setOriginalFileName(f.getUpload().getFileName());

dao.insertData("img.insertData", f);

}

return mapping.findForward("write_ok");

}

//파일 리스트

public ActionForward list(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

MyUtil myUtil = new MyUtil();

String cp = request.getContextPath();

int numPerPage = 9;

int totalPage = 0;

int totalDataCount = 0;

String pageNum = request.getParameter("pageNum");

int currentPage = 1;

if(pageNum!=null&&!pageNum.equals("")){

currentPage = Integer.parseInt(pageNum);

}

totalDataCount = dao.getIntValue("img.dataCount");

if(totalDataCount!=0)

totalPage = myUtil.getPageCount(numPerPage, totalDataCount);

if(currentPage>totalPage)

currentPage = totalPage;

Map<String, Object> hMap = new HashMap<String,Object>();

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

int end = currentPage*numPerPage;

hMap.put("start", start);

hMap.put("end", end);

List<Object> lists = (List<Object>)dao.getListData("img.listData",hMap);

//번호 재정렬 작업

Iterator<Object> it = lists.iterator();

int listNum,n=0;

String str;

while(it.hasNext()){

ImageForm dto = (ImageForm)it.next();

listNum = totalDataCount - (start + n - 1) ;

dto.setListNum(listNum);

n++;

str = cp + "/img.do?method=download&num="+dto.getNum();

dto.setUrlFile(str);

}

String urlList = cp + "/img.do?method=list";

// 이미지파일경로

String imagePath = cp + "/pds/imageFile";

request.setAttribute("imagePath", imagePath);

request.setAttribute("currentPage", currentPage);

request.setAttribute("lists", lists);

request.setAttribute("pageNum", pageNum);

request.setAttribute("totalPage", totalPage);

request.setAttribute("totalDataCount", totalDataCount);

request.setAttribute("pageIndexList", myUtil.pageIndexList(currentPage, totalPage, urlList));

return mapping.findForward("list");

}

//파일 삭제

public ActionForward delete(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

//DB연결 및 세션가져오기

CommonDAO dao = CommonDAOImpl.getInstance();

HttpSession session = request.getSession();

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" +  File.separator + "imageFile";

int num = Integer.parseInt(request.getParameter("num"));

//삭제해야하는 데이터 값 읽어오기

ImageForm dto = (ImageForm)dao.getReadData("img.readData", num);

String saveFileName = dto.getSaveFileName();

//파일삭제

FileManager.doFileDelete(saveFileName, savePath);

//DB삭제

dao.deleteData("img.deleteData",num);

return mapping.findForward("delete");

}

//파일 다운로드

public ActionForward download(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

//DB연결 및 세션가져오기

CommonDAO dao = CommonDAOImpl.getInstance();

HttpSession session = request.getSession();

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" +  File.separator + "imageFile";

int num = Integer.parseInt(request.getParameter("num"));

//다운로드 받을 데이터값 읽어오기

ImageForm dto = (ImageForm)dao.getReadData("img.readData", num);

if(dto==null){

return mapping.findForward("list");

}

//다운로드 진행

boolean flag = FileManager.doFileDownload(dto.getSaveFileName(),

dto.getOriginalFileName(), savePath, response);

if(!flag){

//다운로드 받지 못했을 시 실행

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

out.print("<script type='text/javascript'>");

out.print("alert('다운로드 에러!!!');");

out.print("history.back();");

out.print("</script>");

}

//다운로드 후 페이지 변동이 없으므로 반환값을 null로 줌

return mapping.findForward(null);

}

}

8. 이미지 등록 페이지 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" />

<link rel="stylesheet" href="<%=cp %>/imageTest/css/created.css" type="text/css" />

<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.upload.value;

   if(!str) {

       alert("이미지 파일을 선택 하세요 !!!");

       f.upload.focus();

       return;

   }

   f.action= "<%=cp%>/img.do?method=write_ok";

   f.submit();

}s

</script>

</head>

<body>

<form action="<%=cp%>/img.do" method="post" enctype="multipart/form-data" name="myForm" >

<table cellpadding="2" id="bbs">

<tr>

<td id="bbs_title" colspan="3">

이미지 등록

</td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr>

<td align="center" width="100">제&nbsp;&nbsp;&nbsp;&nbsp;목</td>

<td colspan="2" >

<input type="text" name="subject" class="boxTF" size="74"/></td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr>

<td align="center">파&nbsp;&nbsp;&nbsp;&nbsp;일</td>

<td class="bbsCreated_bottomLine" colspan="2" >

<input type="file" name="upload" class="boxTF" size="74"/></td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr id="bbsCreated_footer">

<td colspan="3" align="center">

<input type="hidden" value="write_ok" name="method">

<input type="button" value="파일등록" onclick="sendIt()"/>

<input type="button" value="다시입력" onclick="document.myForm.subject.focus();"/>

<input type="button" value="작성취소" onclick="javascript:location.href='<%=cp %>/img.do?method=list';"/></td>

</tr>

</table>

</form>

</body>

</html>

9. 이미지 리스트 조회페이지

<%@ 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" align="center" style="font-family: 돋움; font-size: 10pt;" cellspacing="2" cellpadding="1" >

<tr id="bbsList">

<td id="bbsList_title" colspan="3">

이미지 게시판

</td>

</tr>

</table>

<table width="600" border="0" cellpadding="0" cellspacing="0" align="center">

 <tr height="30">

    <td align="left" width="50%">

      Total ${totalDataCount} articles, ${totalPage} pages / Now page is ${currentPage}

    </td>

    <td align="right">

      <input type="button" value=" 게시물 등록 " onclick="javascript:location.href='<%=cp%>/img.do?method=write'" class="btn1"/>

    </td>

  </tr>

</table>

<table width="600" border="0" cellpadding="0" cellspacing="0" align="center">

<tr><td height="3" bgcolor="#DBDBDB" align="center"></td></tr>

</table>

<table width="600" border="0" cellspacing="1" cellpadding="3"

bgColor="#FFFFFF" align="center">

<c:set var="n" value="0"/>

<c:forEach var="dto" items="${lists}">

<c:if test="${n==0}">

<tr bgcolor="#FFFFFF" ></tr>

</c:if>

<c:if test="${n!=0&&n%3==0 }">

<tr bgcolor="#FFFFFF" ></tr>

</c:if>

    <td width="200" align="center">

    <a href="${imagePath}/${dto.saveFileName}">

   <img src="${imagePath}/${dto.saveFileName}" width="180" height="180" border="0" />

  </a>

   <br/>${dto.subject}&nbsp;<a href="<%=cp%>/img.do?method=delete&num=${dto.num}">삭제</a>

</td>

<c:set var="n" value="${n+1}"/>

</c:forEach>

<c:if test="${n>0||n%3!=0 }">

<c:forEach var="i" begin="${n%3+1}" end="3" step="1">

<td>&nbsp;</td>

</c:forEach>

</c:if>

<c:if test="${n!=0 }">

</tr>

</c:if>

<c:if test="${totalDataCount != 0}">

<tr bgcolor="#FFFFFF">

  <td align="center" height="30" colspan="3">${pageIndexList}</td>

  </tr>

</c:if>

<c:if test="${totalDataCount == 0}">

<tr bgcolor="#FFFFFF">

     <td align="center" colspan="3" height="30">등록된 자료가 없습니다.</td>

  </tr>

</c:if>

</table>

<table width="600" border="0" cellpadding="0" cellspacing="0" align="center">

<tr><td height="3" bgcolor="#DBDBDB" align="center"></td></tr>

</table>

</body>

</html>