🍁MVC Model
MVC는 소프트웨어를 구성하는 패턴 중 하나로, 소프트웨어를 구조화하고 코드를 관리하기 위한 디자인 패턴이다.
- MVC(Model View Controller)
- DAO(Data Access Object)
- DTO(Data Transfer Object)
Model: 애플리케이션의 데이터와 비즈니스 로직을 담당한다.
View: 사용자 인터페이스와 관련된 부분으로, 데이터의 시각적 표현을 담당한다.
Controller: 사용자 입력을 처리하고 Model과 View 간의 상호 작용을 조정한다.
DAO (Data Access Object)
DAO는 데이터베이스와 관련된 작업을 전문적으로 수행하는 객체로, 주로 CRUD 작업 (Create, Retrieve, Update, Delete)을 수행하는 메서드를 제공한다.
데이터베이스와 상호작용하는 로직을 캡슐화하고, 데이터베이스 연결 및 쿼리 실행을 처리한다.
일반적으로 JDBC나 ORM(Object-Relational Mapping) 프레임워크를 사용하여 데이터베이스와 통신한다.
DTO (Data Transfer Object)
DTO는 데이터 전송을 위한 객체로, 주로 데이터베이스 테이블(Entity)의 열(Column)에 해당하는 필드를 포함한다.
DTO 객체는 데이터를 보관하고 전송하는 역할을 한다. 일반적으로 Getter와 Setter 메서드를 제공하여 데이터에 접근하고 설정할 수 있다.
주로 데이터 전송과 데이터 저장을 위해 사용되며, 데이터베이스 레코드를 자바 객체로 매핑하는 데 사용될 수 있다.
Hello.java
package com.test.mvc;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Servlet을 호출해서 업무를 처리한다
//HTML에서 페이지를 생산하는 게 불편하기 때문에 JSP에 위임한다.
//resp.sendRedirect("/mvc/hello.jsp");
//DB작업에서 select count(*)
int count=100;
//서블릿이 자신의 업무를 완료하고 산출물의 일부를 출력하는데 JSP 페이지 전달한다.
req.setAttribute("count", count);
//resp.sendRedirect("/mvc/hello.jsp");
//pageContext.forward("/mvc/hello.jsp");
//'/'는 webapp를 의미한다.
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/hello.jsp");
dispatcher.forward(req, resp); //pageContext.forward();
}
}
Hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="http://pinnpublic.dothome.co.kr/cdn/example-min.css">
</head>
<body>
<h1>Hello</h1>
<div>count : <%= request.getAttribute("count") %></div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://pinnpublic.dothome.co.kr/cdn/example-min.js"></script>
</body>
</html>
🍁Memo
메모장은 위와 같은 과정으로 작업이 실행된다.
🍁소스코드
Ok가 붙은 경우에만 DB 작업을 한다.
MVC 기반
1. 주제 > 메모장
2. 업무 > CRUD
- 메모 쓰기(C)
- 메모 목록(R)
- 메모 읽기(R)
- 메모 수정(U)
- 메모 삭제(D)
3. DB
- Memo > "script.sql"
4. 파일
- 공통 파일
- webapp > "inc" > "header.jsp", "asset.jsp"
파일 구성
- 메모 쓰기
- com.test.memo > Add.java, AddOk.java
- webapp > WEB-INF > views > add.jsp, addok.jsp
- 메모 목록
- com.test.memo > List.java
- webapp > WEB-INF > views > list.jsp
- 메모 읽기
- com.test.memo > View.java
- webapp > WEB-INF > views > view.jsp
- 메모 수정
- com.test.memo > Edit.java, EditOk.java
- webapp > WEB-INF > views > edit.jsp, editok.jsp
- 메모 삭제
- com.test.memo > Del.java, DelOk.java
- webapp > WEB-INF > views > del.jsp, delok.jsp
- 템플릿
- com.test.memo > Template.java
- webapp > WEB-INF > view > template.jsp
- JDBC
- com.test.memo > DBUtil.java 복사
- WEB-INF > lib > ojdb6.jar 복사
- DB 담당자
- com.test.memo
- com.test.memo.repository > MemoDAO.java
- com.test.memo.dao
- com.test.memo.model > MeMoDTO.java
- com.test.memo.dto
- JSTL 설치
- WEB-INF > lib > jstl-1.2.jar 복사
DB
DBUtil
package com.test.memo;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil {
private static Connection conn;
public static Connection open() {
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "hr";
String pw = "java1234";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, id, pw);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Connection open(String server, String id, String pw) {
String url = "jdbc:oracle:thin:@" + server + ":1521:xe";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, id, pw);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
script.sql
-- Memo > script.sql
drop table tblMemo;
drop sequence seqMemo;
create table tblMemo (
seq number primary key, -- 번호(PK)
name varchar2(30) not null, -- 이름
pw varchar2(30) not null, -- 암호(메모)
memo varchar2(2000) not null, -- 메모
regdate date default sysdate not null -- 날짜
);
create sequence seqMemo;
-- 메모 쓰기
insert into tblMemo (seq, name, pw, memo, regdate) values (seqMemo.nextVal, 'Isaac', '1111', '메모입니다.', default);
-- 메모 목록
select * from tblMemo order by seq desc;
-- 메모 읽기
select * from tblMemo where seq = 1;
-- 메모 수정
update tblMemo set memo = '수정 내용' where seq = 1;
-- 메모 삭제
delete from tblMemo where seq = 1;
commit;
메모 쓰기
Add.java
package com.test.memo;
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);
}
}
AddOk.java
package com.test.memo;
import java.io.IOException;
import java.sql.Connection;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@WebServlet("/addok.do")
public class AddOk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//AddOk.java
//1. 데이터 가져오기(name, pw, memo)
//2. DB 작업 > insert
//3. 피드백(X) > JSP 호출하기
//1.
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
String pw = req.getParameter("pw");
String memo = req.getParameter("memo");
//2. DB
// 계층(AddOk) > 데이터(포장 - HashMap or 객체) > 계층(MemoDAO)
MemoDAO dao = new MemoDAO();
MemoDTO dto = new MemoDTO();
dto.setName(name);
dto.setPw(pw);
dto.setMemo(memo);
//dao.add(name, pw, memo);
int result = dao.add(dto); //넘기는 데이터 2개 이상 > DTO 담아서
//3.
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/addok.jsp");
dispatcher.forward(req, resp);
}
}
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ include file="/WEB-INF/views/inc/asset.jsp"%>
<style>
</style>
</head>
<body>
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<form method="POST" action="/memo/addok.do">
<table class="vertical">
<tr>
<th>이름</th>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<th>암호</th>
<td><input type="password" name="pw" required></td>
</tr>
<tr>
<th>메모</th>
<td><textarea name="memo" required class="full"></textarea></td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="location.href='/memo/list.do';">
<input type="submit" value="쓰기">
</div>
</form>
<script>
</script>
</body>
</html>
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">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > addok.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<script>
<%--
<% if ((int)request.getAttribute("result") == 1) { %>
location.href = '/memo/list.do';
<% } else { %>
alert('실패');
location.href = '/memo/add.do';
<% } %>
--%>
<c:if test="${result == 1}">
location.href = '/memo/list.do';
</c:if>
<c:if test="${result == 0}">
alert('실패');
//location.href = '/memo/add.do'; > 페이지 새로 요청
history.back(); //페이지 새로요청(X) > 이전 상태로 되돌리기
</c:if>
</script>
</body>
</html>
메모 목록
List.java
package com.test.memo;
import java.io.IOException;
import java.util.ArrayList;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@WebServlet("/list.do")
public class List extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//List.java
//1. DB 작업 > select > DAO 위임
//2. 결과 테이블
//3. JSP 호출하기(+ 결과 테이블 전달)
//1. + 2.
MemoDAO dao = new MemoDAO();
ArrayList<MemoDTO> list = dao.list();
//System.out.println(list);
for (MemoDTO dto : list) {
if (dto.getMemo().length() > 12) {
dto.setMemo(dto.getMemo().substring(0, 12) + "..");
}
}
//3.
req.setAttribute("list", list);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/list.jsp");
dispatcher.forward(req, resp);
}
}
list.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">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
#list {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
#list .item {
border: 1px solid #CCC;
cursor: pointer;
}
#list .item div {
padding: 5px;
}
#list .item div:nth-child(2) {
height: 50px;
}
#list .item div:nth-child(odd) {
background-color: #EEE;
}
</style>
</head>
<body>
<!-- template.jsp > list.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<div id="list">
<c:forEach items="${list}" var="dto">
<div class="item"
onclick="location.href='/memo/view.do?seq=${dto.seq}';">
<div>${dto.seq}. ${dto.name}</div>
<div>${dto.memo}</div>
<div>${dto.regdate}</div>
</div>
</c:forEach>
</div>
<div>
<input type="button" value="쓰기"
onclick="location.href='/memo/add.do';">
</div>
<script>
</script>
</body>
</html>
메모 읽기
View.java
package com.test.memo;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@WebServlet("/view.do")
public class View extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//View.java
//1. 데이터 가져오기(seq)
//2. DB 작업 > select > DAO 위임
//3. 결과값 반환 > JSP 호출하기(+전달)
//1.
String seq = req.getParameter("seq");
//2.
MemoDAO dao = new MemoDAO();
MemoDTO dto = dao.get(seq);
dto.setMemo(dto.getMemo().replace("\r\n", "<br>"));
//3.
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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > add.jsp > view.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<table class="vertical">
<tr>
<th>번호</th>
<td>${dto.seq}</td>
</tr>
<tr>
<th>이름</th>
<td>${dto.name}</td>
</tr>
<tr>
<th>메모</th>
<td>${dto.memo}</td>
</tr>
<tr>
<th>날짜</th>
<td>${dto.regdate}</td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="location.href='/memo/list.do';">
<input type="button" value="수정하기" onclick="location.href='/memo/edit.do?seq=${dto.seq}';">
<input type="button" value="삭제하기" onclick="location.href='/memo/del.do?seq=${dto.seq}';">
</div>
<script>
</script>
</body>
</html>
메모 수정
Edit.java
package com.test.memo;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@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 작업 > select > DAO 위임
//3. MemoDTO 반환 > JSP 호출하기(+전달)
//1.
String seq = req.getParameter("seq");
//2.
MemoDAO dao = new MemoDAO();
MemoDTO dto = dao.get(seq);
//3.
req.setAttribute("dto", dto);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/edit.jsp");
dispatcher.forward(req, resp);
}
}
EditOk.java
package com.test.memo;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@WebServlet("/editok.do")
public class EditOk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//EditOk.java
//1. 데이터 가져오기(수정 데이터)
//2. DB 작업 > update > DAO 위임
//3. 결과 > 피드백 > JSP 호출하기
//1.
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
String memo = req.getParameter("memo");
String seq = req.getParameter("seq");
String pw = req.getParameter("pw"); //권한 확인용
//2.
MemoDAO dao = new MemoDAO();
MemoDTO dto = new MemoDTO();
dto.setName(name);
dto.setMemo(memo);
dto.setSeq(seq);
dto.setPw(pw);
boolean flag = dao.check(dto);
int result = 0; //성공(1), 실패(0), 암호틀림(2)
if (flag) {
result = dao.edit(dto);
} else {
result = 2;
}
//3.
req.setAttribute("result", result);
req.setAttribute("seq", seq);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/editok.jsp");
dispatcher.forward(req, resp);
}
}
location과 history
location.href는 페이지를 항상 새로 요청하는데, history.back은 뒤로 가면 add가 나오기 때문에 결과는 똑같다.
location.href = '/memo/add.do';는 이전 페이지로 돌아간다고 하지만 새로운 페이지를 다시 부르는 거고, history.back();은 모든 컨트롤과 상태를 복구한다. 보통은 history.back()이 더 좋지만, 은행과 같은 페이지에서는 보안상 문제가 생길 수 있기 때문에 적합하지 않다.
edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > add.jsp > edit.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<form method="POST" action="/memo/editok.do">
<table class="vertical">
<tr>
<th>이름</th>
<td><input type="text" name="name" required value="${dto.name}"></td>
</tr>
<tr>
<th>암호</th>
<td><input type="password" name="pw" required></td>
</tr>
<tr>
<th>메모</th>
<td>
<textarea name="memo" required class="full">${dto.memo}</textarea>
</td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="location.href='/memo/list.do';">
<input type="submit" value="수정하기">
</div>
<input type="hidden" name="seq" value="${dto.seq}">
</form>
<script>
</script>
</body>
</html>
editok.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">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > addok.jsp > editok.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<script>
<c:if test="${result == 1}">
location.href = '/memo/view.do?seq=${seq}';
</c:if>
<c:if test="${result == 0}">
alert('실패');
history.back();
</c:if>
<c:if test="${result == 2}">
alert('암호 틀림');
history.back();
</c:if>
</script>
</body>
</html>
메모 삭제
Del.java
package com.test.memo;
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("/del.do")
public class Del extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Del.java
//1. 데이터 가져오기(seq)
//2. JSP 호출하기
//1.
String seq = req.getParameter("seq");
//2.
req.setAttribute("seq", seq);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/del.jsp");
dispatcher.forward(req, resp);
}
}
DelOk.java
package com.test.memo;
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.test.memo.model.MemoDTO;
import com.test.memo.repository.MemoDAO;
@WebServlet("/delok.do")
public class DelOk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//DelOk.java
//1. 데이터 가져오기(seq, pw)
//2. 암호 확인 > 권한?
//3. DB 작업 > delete > DAO 위임
//4. 피드백 > JSP 호출하기
//1.
String seq = req.getParameter("seq");
String pw = req.getParameter("pw");
//2.
MemoDAO dao = new MemoDAO();
MemoDTO dto = new MemoDTO();
dto.setSeq(seq);
dto.setPw(pw);
int result = 0;
if (dao.check(dto)) {
result = dao.del(seq);
} else {
result = 2;
}
//3.
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/delok.jsp");
dispatcher.forward(req, resp);
}
}
del.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > add.jsp > edit.jsp > del.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<form method="POST" action="/memo/delok.do">
<table class="vertical">
<tr>
<th>암호</th>
<td><input type="password" name="pw" required></td>
</tr>
</table>
<div>
<input type="button" value="돌아가기" onclick="location.href='/memo/list.do';">
<input type="submit" value="삭제하기">
</div>
<input type="hidden" name="seq" value="${seq}">
</form>
<script>
</script>
</body>
</html>
delok.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">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp > addok.jsp > editok.jsp > delok.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
<script>
<c:if test="${result == 1}">
location.href = '/memo/list.do';
</c:if>
<c:if test="${result == 0}">
alert('실패');
history.back();
</c:if>
<c:if test="${result == 2}">
alert('암호 틀림');
history.back();
</c:if>
</script>
</body>
</html>
🍂DB 담당자
MemoDAO.java
package com.test.memo.model;
//계층간 데이터를 전달하는 상자 역할 > Model
//- DTO > Data Transfer Object
// > 멤버 변수 + Getter/Setter 구현
//MemoDTO == tblMemo의 레코드 1줄
public class MemoDTO {
private String seq;
private String name;
private String pw;
private String memo;
private String regdate;
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
MeMoDTO.java
package com.test.memo.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.test.memo.DBUtil;
import com.test.memo.model.MemoDTO;
public class MemoDAO {
private Connection conn;
private Statement stat;
private PreparedStatement pstat;
private ResultSet rs;
public MemoDAO() {
this.conn = DBUtil.open();
}
public int add(MemoDTO dto) {
//DTO > insert
try {
String sql = "insert into tblMemo (seq, name, pw, memo, regdate) values (seqMemo.nextVal, ?, ?, ?, default)";
pstat = conn.prepareStatement(sql);
pstat.setString(1, dto.getName());
pstat.setString(2, dto.getPw());
pstat.setString(3, dto.getMemo());
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public ArrayList<MemoDTO> list() {
ArrayList<MemoDTO> list = new ArrayList<MemoDTO>();
try {
String sql = "select * from tblMemo order by seq desc";
stat = conn.createStatement();
rs = stat.executeQuery(sql);
//rs == 메모 목록
//rs > list
while (rs.next()) {
//레코드 1줄 > MemoDTO 1개
MemoDTO dto = new MemoDTO();
dto.setSeq(rs.getString("seq"));
dto.setName(rs.getString("name"));
dto.setPw(rs.getString("pw"));
dto.setMemo(rs.getString("memo"));
dto.setRegdate(rs.getString("regdate"));
list.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public MemoDTO get(String seq) {
try {
String sql = "select * from tblMemo where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, seq);
rs = pstat.executeQuery();
MemoDTO dto = new MemoDTO();
if (rs.next()) {
dto.setSeq(rs.getString("seq"));
dto.setName(rs.getString("name"));
dto.setPw(rs.getString("pw"));
dto.setMemo(rs.getString("memo"));
dto.setRegdate(rs.getString("regdate"));
return dto;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int edit(MemoDTO dto) {
try {
String sql = "update tblMemo set name =?, memo = ? where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, dto.getName());
pstat.setString(2, dto.getMemo());
pstat.setString(3, dto.getSeq());
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public boolean check(MemoDTO dto) {
try {
String sql = "select count(*) as cnt from tblMemo where seq = ? and pw = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, dto.getSeq());
pstat.setString(2, dto.getPw());
rs = pstat.executeQuery();
if (rs.next()) {
return rs.getInt("cnt") == 1 ? true : false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public int del(String seq) {
try {
String sql = "delete from tblMemo where seq = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, seq);
return pstat.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
템플릿
Template.java
package com.test.memo;
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("/template.do")
public class Template extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher dispatcher
= req.getRequestDispatcher("/WEB-INF/views/template.jsp");
dispatcher.forward(req, resp);
}
}
- Java > Editor > Templates
New 버튼을 클릭하고 코드를 추가하여 템플릿을 생성한다.
template.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">
<%@ include file="/WEB-INF/views/inc/asset.jsp" %>
<style>
</style>
</head>
<body>
<!-- template.jsp -->
<%@ include file="/WEB-INF/views/inc/header.jsp" %>
목록보기, 메모쓰기, 수정, 삭제 등..
<script>
</script>
</body>
</html>