728x90
★ 이미지 뷰어(갤러리)
- CR
- 유저 1명
- 사진(이미지) + 이름 + 날짜 + 설명 등 ...
- 파일 업로드 + DB 연동
★ VO vs DTO
- 데이터를 저장하는 객체
- 자바 클래스
- VO : Value Object
- DB에서 가져온 데이터를 보관하는 용도
- 읽기 전용 > 리터럴(상수)
- DTO : Data Transfer Object
- 계층간에 데이터를 전송할 때 사용되는 도구(택배 상자)
- 수정이 가능하다.
- 목록보기 : DB > DAO > (VO) > 컨트롤러 > (VO) > JSP
- 글쓰기 : JSP > 컨트롤러 > (DTO) > DAO > DB
■ 필요 파일
- com.test.file > "List.java" //시작 페이지
> "Add.java"
> "AddOk.java"
> "View.java"
> "FileDAO.java"
> "FileDTO.java"
> "Edit.java"
> "EditOk.java"
> "DelOk.java"
- views > "list.jsp"
> "add.jsp"
> "addok.jsp"
> "view.jsp"
> "edit.jsp"
> "editok.jsp"
> "delok.jsp"
- views > "inc" > "header.jsp"
■ DB 파일 생성
- script.sql
- 1. 파일을 직접 DB에 저장 > 바이너리(이진 파일) 저장
- 2. 파일은 하드에 저장 > DB에는 파일명(텍스트)만 저장 > 주로 사용!!
create table tblFile (
seq number primary key, --번호(PK)
name varchar2(30) not null, -- 작성자
filename varchar2(50) not null, -- 파일명(하드에 저장되는 이름)
regdate date default sysdate not null --날짜
);
create sequence seqFile;
■ FileDTO.java : 데이터를 저장하는 용도로 사용
- 멤버변수, Getter, Setter
package com.test.file;
public class FileDTO {
private String seq;
private String name;
private String filename;
private String regdate;
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
}
■ FileDAO.java : 데이터 액세스 오브젝트, DB 작업 담당자
package com.test.file;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.test.my.DBUtil;
//DAO, Data Access Object
//- DB 작업 담당자
public class FileDAO {
private Connection conn;
private Statement stat;
private PreparedStatement pstat;
private ResultSet rs;
public FileDAO() {
this.conn = DBUtil.open();
}
public int add(FileDTO dto) {
try {
String sql = "insert into tblFile (seq, name, filename, regdate) values (seqFile.nextVal, ?, ?, default)";
pstat = conn.prepareStatement(sql);
pstat.setString(1, dto.getName());
pstat.setString(2, dto.getFilename());
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public List<FileDTO> list() {
try {
String sql = "select seq, filename from tblFile order by seq desc";
stat = conn.createStatement();
rs = stat.executeQuery(sql);
List<FileDTO> list = new ArrayList<FileDTO>();
//ResultSet > (복사) > ArrayList
while (rs.next()) {
//레코드 1줄 > FileDTO 1개
FileDTO dto = new FileDTO();
dto.setSeq(rs.getString("seq"));
dto.setFilename(rs.getString("filename"));
list.add(dto);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public FileDTO get(String seq) {
try {
String sql = "select * from tblFile where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, seq);
rs = pstat.executeQuery();
if (rs.next()) {
//레코드 1줄 > DTO 1개
FileDTO dto = new FileDTO();
dto.setSeq(rs.getString("seq"));
dto.setName(rs.getString("name"));
dto.setFilename(rs.getString("filename"));
dto.setRegdate(rs.getString("regdate"));
return dto;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int edit(FileDTO dto) {
try {
String sql = "";
if(dto.getFilename() != null && !dto.getFilename().equals("")) {
sql = "update tbl File set name = ?, filename = ? where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1,dto.getName());
pstat.setString(2,dto.getFilename());
pstat.setString(3,dto.getSeq());
} else {
sql = "update tblFile set name = ? where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1,dto.getName());
pstat.setString(2,dto.getSeq());
}
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
■ List.java : DB 작업 > DAO 위임 > select ...
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/list.do")
public class List extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//List.java
//1. DB 작업 > DAO 위임 > select...
//2. 결과 반환(List<FileDTO>)
//3. JSP 호출하기
FileDAO dao = new FileDAO();
java.util.List<FileDTO> list = dao.list();
req.setAttribute("list", list);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/list.jsp");
dispatcher.forward(req, resp);
}
}
■ List.jsp : 리스트 페이지 UI 작업 및 실제적 구현
<%@ 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>Image Viewer</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
img {
display:block;
width : 140px;
height : 140px;
margin : 0 auto;
object-fit : cover;
cursor : pointer;
}
</style>
</head>
<body>
<h1>Image Viewer</h1>
<table>
<tr>
<c:forEach items="${list}" var="dto" varStatus="status">
<td><img src="/file/files/${dto.filename}" onclick="view(${dto.seq});"></td>
<c:if test="${status.count % 5 == 0}">
</tr>
<tr>
</c:if>
</c:forEach>
<c:forEach var="i" begin="1" end="${5- list.size() % 5}">
<td></td>
</c:forEach>
</tr>
</table>
<div>
<input type="button" value="등록하기" onclick="location.href='/file/add.do';">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function view(seq) {
location.href = '/file/view.do?seq=' + seq;
}
</script>
</body>
</html>
■ add.java : 등록 servlet
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/add.do")
public class Add extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Add.java
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/add.jsp");
dispatcher.forward(req, resp);
}
}
■ add.jsp : 등록 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>ImageViewer</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<h1>Image Viewer</h1>
<form method="POST" action="/file/addok.do" enctype="multipart/form-data">
<table>
<tr>
<th>작성자</th>
<td><input type="text" name="name" class="short" required></td>
</tr>
<tr>
<th>이미지</th>
<td><input type="file" name="attach" required accept=".gif, .png, .jpg, .jpeg"></td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="history.back();">
<input type="submit" value="등록하기">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
■ AddOk.java
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
@WebServlet("/addok.do")
public class AddOk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//AddOk.java
//1. 파일 업로드 처리
//2. DB 처리
String name = "";
String filename = "";
try {
MultipartRequest multi = new MultipartRequest(
req,
req.getRealPath("/files"),
1034 *1024 *100,
"UTF-8",
new DefaultFileRenamePolicy()
);
System.out.println(req.getRealPath("/files"));
filename = multi.getFilesystemName("attach");
name = multi.getParameter("name");
} catch (Exception e) {
// TODO: handle exception
}
//2.
FileDAO dao = new FileDAO();
FileDTO dto = new FileDTO();
dto.setName(name);
dto.setFilename(filename);
int result = dao.add(dto); //성공(1), 실패(0)
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/addok.jsp");
dispatcher.forward(req, resp);
}
}
■ addok.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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
<c:if test="${result == 1}">
location.href = '/file/list.do';
</c:if>
<c:if test="${result == 0}">
alert('failed');
history.back();
</c:if>
</script>
</body>
</html>
■ View.java
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/view.do")
public class View extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//View.java
//- view.do?seq=12
//1. 번호 가저오기
//2. DB 작업 > DAO 위임 > select where seq = 12
//3. 결과 반환 > JSP 호출하기
String seq = req.getParameter("seq");
FileDAO dao = new FileDAO();
FileDTO dto = dao.get(seq);
req.setAttribute("dto", dto);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/view.jsp");
dispatcher.forward(req, resp);
}
}
■ view.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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
img {
display : block;
margin : 50px auto;
max-width : 750px;
}
</style>
</head>
<body>
<h1>Image Viewer</h1>
<table>
<tr>
<td colspan="2"><img src="/file/files/${dto.filename}"></td>
</tr>
<tr>
<td>${dto.name}</td>
<td>${dto.regdate}</td>
</tr>
</table>
<div>
<input type="button" value="돌아가기"
onclick = "location.href='/file/list.do';">
<input type="button" value="수정하기"
onclick = "location.href='/file/edit.do';">
<input type="button" value="삭제하기"
onclick = "location.href='/file/del.do';">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
■ Edit.java
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/edit.do")
public class Edit extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Edit.java
//1. 번호 가져오기(seq)
//2. DB 작업 > DAO 위임 > select
//3. 결과 반환 > JSP 호출하기
String seq = req.getParameter("seq");
FileDAO dao = new FileDAO();
FileDTO dto = dao.get(seq);
req.setAttribute("dto", dto);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/edit.jsp");
dispatcher.forward(req, resp);
}
}
■ edit.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>ImageViewer</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<h1>Image Viewer</h1>
<form method="POST" action="/file/editok.do" enctype="multipart/form-data">
<table>
<tr>
<th>작성자</th>
<td><input type="text" name="name" class="short" required value="${dto.name}"></td>
</tr>
<tr>
<th>이미지</th>
<td>
<input type="file" name="attach" required>
<span>${dto.filename}</span>
</td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="history.back();">
<input type="submit" value="수정하기">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$('input[name=attach]').change(function() {
if ($(this).val() != '') {
$(this).next().css('text-decoration', 'line-through');
}else {
$(this).next().css('text-decoration', 'none');
}
});
</script>
</body>
</html>
■ EditOk.java
package com.test.file;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
@WebServlet("/editok.do")
public class EditOk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//EditOk.java
//1. 데이터 가져오기
//2. DB 작업 > DAO 위임 > update
//3. 첨부 파일 교체
String name = "";
String filename = "";
try {
MultipartRequest multi = new MultipartRequest(
req,
req.getRealPath("/files"),
1034 *1024 *100,
"UTF-8",
new DefaultFileRenamePolicy()
);
System.out.println("attach : " + multi.getFilesystemName("attach"));
name = multi.getParameter("name");
filename = multi.getFilesystemName("attach");
} catch (Exception e) {
e.printStackTrace();
}
FileDAO dao = new FileDAO();
FileDTO dto = new FileDTO();
dto.setName(name);
dto.setFilename(filename);
int result = dao.edit(dto);
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/editok.jsp");
dispatcher.forward(req, resp);
}
}
■ DelOk.java
package com.test.file;
import java.io.File;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/delok.do")
public class DelOk extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//DelOk.java
//1. 데이터 가져오기(seq)
//3. 파일 삭제
//2. DB 작업 > DAO 위임 > delete
String seq = req.getParameter("seq");
FileDAO dao = new FileDAO();
//사진 삭제 > 사진명?
FileDTO dto = dao.get(seq);
try {
File file = new File(req.getRealPath("/files") + "\\" + dto.getFilename());
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
int result = dao.remove(seq);
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/delok.jsp");
dispatcher.forward(req, resp);
}
}
■ delok.java
<%@ 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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
<c:if test="${result == 1}">
location.href = '/file/list.do';
</c:if>
<c:if test="${result == 0}">
alert('failed');
history.back();
</c:if>
</script>
</body>
</html>
■ 실행 결과
- 첫 페이지
- 등록하기
- 등록 완료
- 수정하기
- 수정완료
- 삭제 하기
728x90
'Server' 카테고리의 다른 글
Servlet + JSP STEP 4 - Memo (0) | 2023.05.15 |
---|---|
AJAX STEP 1 - 기초 (0) | 2023.05.12 |
Servlet + JSP STEP 2 - FileProject (0) | 2023.05.12 |
Servlet+JSP STEP 1 - File UPLOAD (0) | 2023.05.11 |
JSTL STEP 1 - JSTL 기초 셋팅 및 응용 (0) | 2023.05.11 |