본문 바로가기
[ View ]/JSP

[ JSP ] Mybatis 응용 예제(방명록)

by 환이s 2023. 3. 19.

이전 포스팅에 이어서 Mybatis 응용 예제 포스팅을 해보겠습니다. 이전 포스팅에서는 한 줄 메모장을 만들어서 기능 확인까지 했습니다. 오늘은 방명록 기능을 만들어 봅시다.

 

 

■  방명록 기능 구조

 

방명록 기능은 글쓰기, 수정과 삭제, 그리고 해당 방명록 찾기 기능을 구현해 보겠습니다.

 

Contoller

GuestBookController.java

Model

GuestBookDTO.java
GuestBookDAO.java

View

index.jsp : 시작 페이지
list.jsp : 방명록 목록
write.jsp : 글쓰기
edit.jsp : 수정, 삭제 기능

■  DB 테이블 생성 

 

<Table 생성 > 

create table guestbook(
idx int not null primary key,
name varchar2(50) not null,
email varchar2(50) not null,
passwd varchar2(50) not null,
content varchar2(2000) not null,
post_date date default sysdate
);

<시퀀스 생성>

create sequence guestbook_seq start with 1
increment by 1
nomaxvalue
nocache;

<데이터 추가>

insert into guestbook (idx,name,email,passwd,content)
values (guestbook_seq.nextval, 'kim', 'kim@daum.net' , '1234', '첫번째 게시물');

데이터 추가까지 완료했다면 select문으로 확인해 봅시다. 

그리고 꼭 잊지 말고 COMMIT! 해주기.

 


■  시작 페이지 생성(indxe.jsp)

시작 페이지는 최대한 간단하게 만들어서 Controller 요청을 보내기 위해 response 객체를 사용했습니다.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>index</title>

<script src="../include/jquery-3.6.3.min.js"></script>

<%@ include file="../include/header.jsp" %>

</head>

<body>

<%

String context = request.getContextPath();

//컨트롤러 이동

response.sendRedirect(context+"/guestbook_servlet/list.do");

%>

</body>

</html>


■  DTO 생성

 

package guestbook.dto;

public class GuestBookDTO {

private int idx;

private String name;

private String email;

private String passwd;

private String content;

private String post_date;

 

public int getIdx() {

return idx;

}

public void setIdx(int idx) {

this.idx = idx;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getPasswd() {

return passwd;

}

public void setPasswd(String passwd) {

this.passwd = passwd;

}

public String getContent() {

return content;

}

public void setContent(String content) {

this.content = content;

}

public String getPost_date() {

return post_date;

}

public void setPost_date(String post_date) {

this.post_date = post_date;

}

@Override

public String toString() {

return "GuestBookDTO [idx=" + idx + ", name=" + name + ", email=" + email + ", passwd=" + passwd + ", content="

+ content + ", post_date=" + post_date + "]";

}

public GuestBookDTO(int idx, String name, String email, String passwd, String content, String post_date) {

 

this.idx = idx;

this.name = name;

this.email = email;

this.passwd = passwd;

this.content = content;

this.post_date = post_date;

}

public GuestBookDTO() {

 

}

 

}

 


 

■  Controller 생성

 

package guestbook;

import java.io.IOException;

import java.util.List;

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 guestbook.dao.GuestBookDAO;

import guestbook.dto.GuestBookDTO;

@WebServlet("/guestbook_servlet/*")

public class guestbookController extends HttpServlet {

private static final long serialVersionUID = 1L;

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String uri = request.getRequestURI();

System.out.println(uri);

GuestBookDAO dao = new GuestBookDAO();

 

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

//검색옵션과 검색 키워드

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

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

 

//검색옵션, 검색키워드에 기본 값 할당

if(searchkey == null) searchkey ="name";

if(search == null) search ="";

 

System.out.println("searchkey : "+searchkey);

System.out.println("search : "+ search);

 

List<GuestBookDTO> items= dao.getList(searchkey,search);

request.setAttribute("list", items);

request.setAttribute("count", items.size());// 레코드 개수

 

request.setAttribute("searchkey", searchkey);

request.setAttribute("search", search);

 

String page ="/guestbook/list.jsp";

RequestDispatcher rd = request.getRequestDispatcher(page);

rd.forward(request, response);

 

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

 

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

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

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

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

 

GuestBookDTO dto = new GuestBookDTO();

 

dto.setName(name);

dto.setEmail(email);

dto.setPasswd(passwd);

dto.setContent(content);

 

dao.gbInsert(dto); //dao에 레코드 추가 요청

 

//방명록 목록 갱신

String url ="/guestbook_servlet/list.do";

response.sendRedirect(request.getContextPath()+url);

 

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

 

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

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

 

System.out.println("게시물 번호 :"+ idx);

System.out.println("비번 : "+ passwd);

 

boolean result = dao.passwdCheck(idx, passwd);

//비번이 맞으면 true , 틀리면 false 리턴

System.out.println("결과 : "+ result);

String url ="";

 

if(result) {

url="/guestbook/edit.jsp"; //수정용 페이지

 

//게시물 내용을 dto로 리턴받음

GuestBookDTO dto =dao.gbDetail(idx);

//request 영역에 저장

request.setAttribute("dto", dto);

 

}else {

url="/guestbook_servlet/list.do";

}

//화면이동

RequestDispatcher rd = request.getRequestDispatcher(url);

rd.forward(request, response);

 

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

 

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

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

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

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

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

 

GuestBookDTO dto = new GuestBookDTO();

dto.setIdx(idx);

dto.setName(name);

dto.setEmail(email);

dto.setPasswd(passwd);

dto.setContent(content);

 

dao.gbUpdate(dto);

 

//방명록 목록 갱신

String url ="/guestbook_servlet/list.do";

response.sendRedirect(request.getContextPath()+url);

 

 

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

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

// 레코드 삭제

dao.gbDelete(idx);

 

//방명록 목록 갱신

String url ="/guestbook_servlet/list.do";

response.sendRedirect(request.getContextPath()+url);

}

 

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

doGet(request, response);

}

}


■ DAO 생성

 

package guestbook.dao;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

/*import javax.swing.text.AbstractDocument.Content;

*/

import org.apache.ibatis.session.SqlSession;

import guestbook.dto.GuestBookDTO;

import sqlmap.MybatisManager;

public class GuestBookDAO {

 

public List<GuestBookDTO> getList(String searchkey, String search){

SqlSession session= MybatisManager.getInstance().openSession();

 

List<GuestBookDTO> list = null;

if(searchkey.equals("name_content")) { //이름 + 내용

list = session.selectList("gblistAll", "%"+search+"%");

 

}else {

Map<String, String> map = new HashMap<>();

map.put("searchkey", searchkey);

map.put("search", "%"+search+"%");

list = session.selectList("gblist",map);

}

 

 

//selectList("네임스페이스.아이디"); - "네임스페이스는 생략 가능"

// List<GuestBookDTO> list = session.selectList("gblist");

 

//줄바꿈, 특수문자 처리 기능 추가

for(GuestBookDTO dto : list) {

String content = dto.getContent();

 

//태그 처리

content = content.replace("<", "&lt");

content = content.replace(">", "&gt");

 

//줄바꿈 처리

content = content.replace("\n", "<br>");

 

//공백 2문자 이상 처리

content = content.replace(" ", "&nbsp;&nbsp;");

 

//검색키워드 색상 처리

if(!searchkey.equals("name")) {

content = content.replace(search, "<span style='color:red'>"+search+"</span>");

}

 

dto.setContent(content);

}

session.close();

return list;

 

}

//방명록 insert

public void gbInsert(GuestBookDTO dto) {

SqlSession session= MybatisManager.getInstance().openSession();

session.insert("gbInsert", dto);

session.commit();

session.close();

 

}

//비밀번호 체크 (idx: 게시물 번호, passwd: 사용자의 비번입력값)

public boolean passwdCheck(int idx, String passwd) {

boolean result = false;

SqlSession session= MybatisManager.getInstance().openSession();

GuestBookDTO dto = new GuestBookDTO();

dto.setIdx(idx);

dto.setPasswd(passwd);

 

//레코드가 1개 리턴

int count = session.selectOne("passwdCheck", dto);

session.close();

 

if(count == 1) {

result = true;

}

 

return result;

}

//게시물 상세정보

public GuestBookDTO gbDetail(int idx) {

GuestBookDTO dto = new GuestBookDTO();

SqlSession session= MybatisManager.getInstance().openSession();

dto = session.selectOne("gbDetail", idx);

session.close();

return dto;

 

}

//게시물 수정

public void gbUpdate(GuestBookDTO dto) {

SqlSession session= MybatisManager.getInstance().openSession();

session.update("guestbook.gbUpdate", dto);

session.commit();

session.close();

 

}

//게시물 삭제

public void gbDelete(int idx) {

SqlSession session= MybatisManager.getInstance().openSession();

session.delete("guestbook.gbDelete", idx);

session.commit();

session.close();

 

}

 

 

}

 

DAO까지 코드 작업을 끝냈다면 이제 Mybatis를 사용하기 위해 mapper 등록 후 페이지를 생성합니다.


■ Mapper page 

 

<mapper page 등록>

<mapper resource="/guestbook/mapper/guestbook.xml"/>

 

<mapper>

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

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="guestbook">

<!-- select에서 resultType="" 반드시 필요하다. -->

<select id="gblist" resultType="guestbook.dto.GuestBookDTO">

select idx,name,email,content,post_date

from guestbook

where ${searchkey} like #{search}

order by idx desc

</select>

<select id="gblistAll" resultType="guestbook.dto.GuestBookDTO">

select idx,name,email,content,post_date

from guestbook

where name like #{search} or content like #{search}

order by idx desc

</select>

<insert id="gbInsert">

insert into guestbook

(idx,name,email,passwd,content) values

(guestbook_seq.nextval, #{name}, #{email} , #{passwd}, #{content})

</insert>

 

<select id="passwdCheck" resultType="int">

select count(*) from guestbook

where idx=#{idx} and passwd=#{passwd}

</select>

 

<select id="gbDetail" parameterType="int" resultType="guestbook.dto.GuestBookDTO">

select * from guestbook

where idx=#{idx}

</select>

 

<update id="gbUpdate" parameterType="guestbook.dto.GuestBookDTO">

update guestbook set name=#{name}, email=#{email}, passwd=#{passwd}, content=#{content}

where idx=#{idx}

</update>

 

<delete id="gbDelete" parameterType="int">

delete from guestbook

where idx=#{idx}

</delete>

</mapper>

 

기능에 맞춰서 SQL문 작성을 맞췄다면  View 단 작업 들어갑니다.


■ View 단

 

<list.jsp : 방명록 목록 페이지>

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>list</title>

<script src="../include/jquery-3.6.3.min.js"></script>

<%@ include file="../include/header.jsp" %>

<script type="text/javascript">

function gb_search() {

document.form1.action="${path}/guestbook_servlet/list.do";

document.form1.submit();

 

}

</script>

</head>

<body>

<h2>방명록</h2>

${count}개의 글이 있습니다.

<!-- 검색 폼 -->

<form name="form1" id="form1" method="post">

<select name="searchkey" id="searchkey">

<c:choose>

<c:when test="${searchkey == 'name'}">

<option value="name" selected>이름</option>

<option value="content">내용</option>

<option value="name_content">이름+내용</option>

</c:when>

<c:when test="${searchkey == 'content'}">

<option value="name">이름</option>

<option value="content" selected>내용</option>

<option value="name_content">이름+내용</option>

</c:when>

<c:when test="${searchkey == 'name_content'}">

<option value="name">이름</option>

<option value="content">내용</option>

<option value="name_content" selected>이름+내용</option>

</c:when>

</c:choose>

</select>

<input name="search" id="search" value="${search}">

<input type="button" value="조회" onclick="gb_search()">

</form>

<input type="button" value="글쓰기" onclick="location.href='${path}/guestbook/write.jsp'">

<input type="button" value="목록" onclick="location.href='${path}/guestbook_servlet/list.do'">

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

<form method="post" action="${path}/guestbook_servlet/passwd_check.do">

<!-- 편집을 위해서는 게시물 번호가 필요함 -->

<input type="hidden" name="idx" value="${dto.idx}">

<table border="1" width="600px">

<tr>

<td>이름</td>

<td>${dto.name}</td>

<td>날짜</td>

<td>${dto.post_date}</td>

</tr>

<tr>

<td>이메일</td>

<td colspan="3">${dto.email}</td>

</tr>

<tr>

<td colspan="4">${dto.content}</td>

</tr>

<tr>

<td colspan="4">

비밀번호 <input type="password" name="passwd">

<input type="submit" value="수정/삭제">

</td>

</tr>

</table>

</form>

</c:forEach>

</body>

</html>


<write.jsp : 글쓰기 페이지>

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>write</title>

<script src="../include/jquery-3.6.3.min.js"></script>

<%@ include file="../include/header.jsp" %>

<script type="text/javascript">

function check() {

document.form1.action="${path}/guestbook_servlet/insert.do";

document.form1.submit();

}

</script>

</head>

<body>

<h2>방명록 작성</h2>

<form name="form1" id="form1" method="post">

<table border="1" width="500px">

<tr>

<td>이름</td>

<td><input name="name" id="name" size="40"></td>

</tr>

<tr>

<td>이메일</td>

<td><input name="email" id="email" size="40"></td>

</tr>

<tr>

<td>비밀번호</td>

<td><input type="password" name="passwd" id="passwd" size="40"></td>

</tr>

<tr align="center">

<td colspan="2"><textarea rows="5" cols="55" name="content" id="content"></textarea> </td>

</tr>

<tr align="center">

<td colspan="2">

<input type="button" value="확인" onclick="check()">

<input type="reset" value="취소">

</td>

</tr>

</table>

</form>

</body>

</html>


<edit.jsp : 수정,삭제 기능 페이지>

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>write</title>

<script src="../include/jquery-3.6.3.min.js"></script>

<%@ include file="../include/header.jsp" %>

<script type="text/javascript">

function gb_update() {

var form1 = $("#form1");

var name = $("#name");

var email = $("#email");

var passwd = $("#passwd");

var content = $("#content");

 

if(name.val() == ""){

alert("이름을 입력하세요.");

name.focus();

return;

}

if(email.val() == ""){

alert("이메일을 입력하세요.");

email.focus();

return;

}

if(passwd.val() == ""){

alert("비밀번호를 입력하세요.");

passwd.focus();

return;

}

if(content.val() == ""){

alert("내용을 입력하세요.");

content.focus();

return;

}

document.form1.action="${path}/guestbook_servlet/update.do";

document.form1.submit();

 

}

function gb_delete() {

if(confirm("삭제하시겠습니까?")){

document.form1.action="${path}/guestbook_servlet/delete.do";

document.form1.submit();

}

}

</script>

</head>

<body>

<h2>방명록 수정/삭제</h2>

<form name="form1" id="form1" method="post">

<table border="1" width="500px">

<tr>

<td>이름</td>

<td><input name="name" id="name" size="40" value="${dto.name}"></td>

</tr>

<tr>

<td>이메일</td>

<td><input name="email" id="email" size="40" value="${dto.email}"></td>

</tr>

<tr>

<td>비밀번호</td>

<td><input type="password" name="passwd" id="passwd" size="40"></td>

</tr>

<tr align="center">

<td colspan="2"><textarea rows="5" cols="55" name="content" id="content">${dto.content}</textarea> </td>

</tr>

<tr align="center">

<td colspan="2">

<input type="hidden" name="idx" value="${dto.idx}">

<input type="button" value="수정" onclick="gb_update()">

<input type="button" value="삭제" onclick="gb_delete()">

<input type="button" value="목록" onclick="location.href='${path}/guestbook_servlet/list.do'">

</td>

</tr>

</table>

</form>

</body>

</html>


■  결과 확인

 

<메인 페이지>

메인 페이지


<글쓰기(데이터 추가)>

글쓰기(데이터 추가)


<방명록 수정/삭제>

방명록 수정

 

방명록 삭제


<방명록 찾기 기능>

방명록 찾기 기능

 


마치며

 

오늘은 지금까지 배운 걸 응용해서 방명록을 만들어봤습니다.

다음 포스팅에서 뵙겠습니다.

 

 

 

728x90

'[ View ] > JSP' 카테고리의 다른 글

[ JSP ] 파일 업로드  (0) 2023.03.23
[ JSP ] 페이지 나누기  (0) 2023.03.22
[ JSP ] Mybatis 응용 예제(한 줄 메모장)  (0) 2023.03.17
[ JSP ] Mybatis 개념 및 설정  (0) 2023.03.16
[ JSP ] JSTL(Jsp Standard Tag Library)  (2) 2023.03.15