Dev/Struts

Struts2/iBatis - 이미지 게시판 구현

창문닦이 2019. 3. 26. 20:51

주요 기능

1. 로그인해야 게시물등록

2. 페이징처리

3. 게시물번호 일렬번호만들기

4. 삭제는 업로드시킨 사람만 삭제가능

1. DB에 테이블 만들기

2. sqlMapConfig 등록

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

3. sqlMap 생성

<?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="member">

<!-- 회원가입 -->

<insert id="insertData" parameterClass="com.join.MemberDTO">

insert into mem (userId,userPwd,userName,userBirth,userTel)

values (#userId#,#userPwd#,#userName#,#userBirth#,#userTel#)

</insert>

<!-- 회원정보찾기 -->

<select id="getId" resultClass="com.join.MemberDTO">

select userId,userPwd,userName,to_char(userBirth,'yyyy-mm-dd') userBirth,userTel

from mem where userId=#userId#

</select>

<!-- 로그인 -->

<select id="getReadData" resultClass="com.join.MemberDTO">

select userId,userPwd,userName,to_char(userBirth,'yyyy-mm-dd') userBirth,userTel

from mem where userId=#userId# and userPwd=#userPwd#

</select>

<!-- 비밀번호찾기 -->

<select id="getPwd" resultClass="com.join.MemberDTO">

select userId,userPwd,userName,to_char(userBirth,'yyyy-mm-dd') userBirth,userTel

from mem where userId=#userId# and userTel=#userTel#

</select>

</sqlMap>

4. struts.xml 등록

 <include file="struts-imageTest.xml"/>

5. struts-imageTest

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

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

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

<struts>

<package name="imageTest" extends="struts-default" namespace="/img" >

 

<action name="created" method="created" class="com.image.ImageAction">

<result name="input" >/imageTest/write.jsp</result>

<result name="success" type="redirectAction">list</result>

</action>

<action name="deleted" method="deleted" class="com.image.ImageAction">

<interceptor-ref name="prepare"/>

<interceptor-ref name="modelDriven"/>

<interceptor-ref name="params"/>

<result name="no" type="chain">

<param name="actionName">list</param>

<param name="namespace">/img</param>

</result>

<result name="success" type="redirectAction">list</result>

</action>

<action name="downView" method="downView" class="com.image.ImageAction">

<result name="success" type="stream">

<param name="inputName">inputStream</param>

<param name="contentType">application/octet-stream</param>

<param name="contentDisposition">fileName=${orifinalFileName}</param>

<param name="bufferSize">1000000</param>

</result>

</action>

<action name="download" method="download" class="com.image.ImageAction">

<!-- 반환값이 null이므로 result는 기재하지 않음 -->

</action>

<action name="list" method="list" class="com.image.ImageAction">

<interceptor-ref name="chain"/>

<interceptor-ref name="prepare"/>

<interceptor-ref name="modelDriven"/>

<interceptor-ref name="params"/>

<result name="success" >/imageTest/list.jsp</result>

</action>

</package>

</struts>

6. ImageDTO 생성

package com.image;

import java.io.File;

public class ImageDTO {

private File upload;//jsp페이지의 input태그의 type=file, name=upload인 데이터

//위에서 정의한 upload에 FileName을 붙이면 Struts2가 자동으로 파일 이름을 넣어준다.

private String uploadFileName; //struts2방식 File클래스 이름뒤에 FileName을 붙임

private String mode;

private int num;

private int listNum;

private String userId;

private String subject;

private String saveFileName;

private String originalFileName;

private String urlFile;//다운로드파일

  getter,setter

}

7. action 클래스 생성

package com.image;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.PrintWriter;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.FileManager;

import com.util.MyUtil;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;

public class ImageAction extends ActionSupport

implements Preparable,ModelDriven<ImageDTO>{

private static final long serialVersionUID = 1L;

private ImageDTO dto;

public ImageDTO getDto() {

return dto;

}

@Override

public ImageDTO getModel() {

return dto;

}

@Override

public void prepare() throws Exception {

dto = new ImageDTO();

}

//이미지파일 업로드

public String created() throws Exception{

//dto.getMode()==null||dto.getMode().equals("") 순서 바뀌면 오류남

if(dto==null||dto.getMode()==null||dto.getMode().equals("")){

return INPUT;

}

HttpServletRequest request = ServletActionContext.getRequest();

HttpSession session = request.getSession();

CommonDAO dao = CommonDAOImpl.getInstance();

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

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

//파일업로드

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

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

if(newFileName!=null){

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

dto.setNum(maxNum+1);

dto.setSaveFileName(newFileName);

//한글인코딩

dto.setOriginalFileName(URLEncoder.encode(dto.getUploadFileName(),"UTF-8"));

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

}

return SUCCESS;

}

//이미지파일 리스트 조회

public String list() throws Exception{

CommonDAO dao = CommonDAOImpl.getInstance();

HttpServletRequest request = ServletActionContext.getRequest();

HttpSession session = request.getSession();

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()){

//전체 데이터 갯수 6개일 때

//리스트번호가 10 8 6 (start=1)/ 5 4 3(start=4) 라 가정

// 1 2 3 / 4 5 6

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

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

dto.setListNum(listNum);

n++;

//파일 다운로드 경로

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

dto.setUrlFile(str);

}

String urlList = cp + "/img/list.action";

// 이미지파일경로

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

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 SUCCESS;

}

//이미지파일 보기

public String downView() throws Exception{

CommonDAO dao = CommonDAOImpl.getInstance();

HttpServletRequest request = ServletActionContext.getRequest();

HttpSession session = request.getSession();

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

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

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

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

dto.setOriginalFileName(new String(dto.getOriginalFileName().getBytes("euc-kr"),"ISO-8859-1"));

String fullFileName = savePath + File.separator + dto.getSaveFileName();

inputStream = new FileInputStream(fullFileName);

return SUCCESS;

}

//이미지파일 다운로드

public String download() throws Exception{

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

CommonDAO dao = CommonDAOImpl.getInstance();

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

HttpSession session = request.getSession();

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

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

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

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

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

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>");

}

return null;

}

//이미지 삭제

public String deleted() throws Exception{

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

CommonDAO dao = CommonDAOImpl.getInstance();

HttpServletRequest request = ServletActionContext.getRequest();

HttpSession session = request.getSession();

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

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

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

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

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

hMap.put("num", num);

hMap.put("userId", userId);

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

ImageDTO dto = (ImageDTO)dao.getReadData("img.readDeleteData", hMap);

if(dto==null){

request.setAttribute("message", "등록자만 삭제가 가능합니다!");

return "no";

}

String saveFileName = dto.getSaveFileName();

//파일삭제

FileManager.doFileDelete(saveFileName, savePath);

//DB삭제

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

return SUCCESS;

}

private InputStream inputStream;//파일보기. 눌렀을때 실행이 되도록

public InputStream getInputStream() {

return inputStream;

}

public void setInputStream(InputStream inputStream) {

this.inputStream = inputStream;

}

}

8. 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" 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/created.action'" class="btn1"/>

      <c:if test="${!empty sessionScope.MemberDTO.userName }">

      <input type="button" value=" 로그아웃 " onclick="javascript:location.href='<%=cp%>/mem/logout.action'" class="btn1"/>

      </c:if>

      <c:if test="${empty sessionScope.MemberDTO.userName }">

      <input type="button" value=" 로그인 " onclick="javascript:location.href='<%=cp%>/mem/login.action'" class="btn1"/>

      </c:if>

    </td>

  </tr>

  <tr>

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

   <c:if test="${!empty sessionScope.MemberDTO.userName }">

${sessionScope.MemberDTO.userName }님 반갑습니다 !

<br>

</c:if>

<font color="red"><b>${message }</b></font>

   </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="<%=cp%>/img/downView.action?num=${dto.num}">

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

</a>

   <br/>[${dto.listNum}]&nbsp;${dto.subject}&nbsp;

   <a href="<%=cp%>/img/deleted.action?num=${dto.num}&userId=${sessionScope.MemberDTO.userId }">삭제</a>&nbsp;

   <a href="<%=cp%>/img/download.action?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>

로그인시 이미지 리스트 게시판

타사용자의 등록 게시물 삭제 시 

로그아웃 시 이미지 리스트 게시판


9. 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.userId.value;

   str = str.trim();

   if(!str) {

       alert("로그인을 하지않으면 작성할 수 없습니다!!!");

       f.userId.focus();

       return;

   }

   f.subject.value = str;

  

   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/created.action";

   f.submit();

}

</script>

</head>

<body>

<form action="<%=cp%>/img/created.action" 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="100px">아&nbsp;이&nbsp;디</td>

<td colspan="2" style="padding-left: 20px;">

<input type="hidden" name="userId" value="${sessionScope.MemberDTO.userId }" />

${sessionScope.MemberDTO.userId }

</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" name="mode" value="save">

<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/list.action';"/>

<input type="button" value="로그인" onclick="javascript:location.href='<%=cp %>/mem/login.action';"/>

</td>

</tr>

</table>

</form>

</body>

</html>

이미지 업로드 페이지

세션에 사용자 아이디 값을 받아 아이디가 없을 경우 오류 발생