spring 28강 Spring Boot와 MongboDB 연동 실습(방명록)
이번 실습에서는 Service ( X )
GuestbookDTO.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.example.spring04.model.guestbook.dto; import java.util.Date; public class GuestbookDTO { private String _id; //key 값 private String name; private String email; private String passwd; private String content; private Date post_date; //getter,setter,toString()... } |
GuestbookDAO.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.example.spring04.model.guestbook.dao; import java.util.List; import com.example.spring04.model.guestbook.dto.GuestbookDTO; public interface GuestbookDAO { public List<GuestbookDTO> getArticleList(); //방명록 목록 public void articleInsert(GuestbookDTO dto); //글쓰기 public void articleUpdate(GuestbookDTO dto); //수정 public void articleDelete(String _id); //삭제 public GuestbookDTO gbDetail(String _id); //상세화면 } |
GuestbookDAOImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package com.example.spring04.model.guestbook.dao; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; import com.example.spring04.model.guestbook.dto.GuestbookDTO; @Repository //dao bean public class GuestbookDAOImpl implements GuestbookDAO { //mongodb 쿼리를 실행시키는 객체 @Autowired MongoTemplate mongoTemplate; //mongodb 실행 객체 //컬렉션(테이블)이름 : guestbook String COLLECTION_NAME="guestbook"; //컬렉션(테이블) 이름 @Override public List<GuestbookDTO> getArticleList() { Query query=new Query(); //날짜 내림차순 정렬 query.with(new Sort(Sort.Direction.DESC, "post_date")); List<GuestbookDTO> list= (List<GuestbookDTO>)mongoTemplate.find( query, GuestbookDTO.class, COLLECTION_NAME); for(GuestbookDTO dto : list) { String content=dto.getContent(); content= content.replace("\r\n", "<br>"); dto.setContent(content); } return list; } |
(List<GuestbookDTO>)mongoTemplate.find( query, GuestbookDTO.class, COLLECTION_NAME)
날짜 내림차순 쿼리 , document 자료형 , 테이블 이름
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //insert 메서드, 포스팅 시간 정보는 안들가기때문에 //insert할 dto에 날짜 정보를 저장한 후 insert @Override public void articleInsert(GuestbookDTO dto) { dto.setPost_date(new Date()); mongoTemplate.insert(dto, COLLECTION_NAME); } @Override public void articleUpdate(GuestbookDTO dto) { // update guestbook set name=?, email=?, content=? // where _id=? //new Criteria("필드명").is(값) //criterion : 기준 System.out.println(dto); Query query= new Query(new Criteria("_id").is(dto.get_id())); //_id가 일치하는 document에 한해서 수정할 내용들을 매핑 Update update=new Update(); update.set("name", dto.getName()); update.set("email", dto.getEmail()); update.set("content", dto.getContent()); //updateFirst : 1개의 레코드만 수정 mongoTemplate.updateFirst(query, update, COLLECTION_NAME); } @Override public void articleDelete(String _id) { Query query=new Query(new Criteria("_id").is(_id)); mongoTemplate.remove(query, COLLECTION_NAME); } @Override public GuestbookDTO gbDetail(String _id) { // findById() 1개의 Document 리턴 // find() Document 리스트 리턴 // findById(_id, 자료형클래스, 컬렉션이름) return mongoTemplate.findById(_id, GuestbookDTO.class , COLLECTION_NAME); } |
gbDetail(String _id)은 /Controller의 gdEdit에서 호출
@RequestMapping("/gbEdit.do")
public ModelAndView gbEdit(String _id)
menu.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <a href="${path}/">Home</a> | <a href="${path}/memo.do">메모장</a> | <a href="${path}/guestbook.do">방명록</a> | <div style="text-align:right;"> <c:choose> <c:when test="${sessionScope.userid == null }"> <a href="${path}/member/login.do">로그인</a> </c:when> <c:otherwise> ${sessionScope.name}님이 로그인중입니다. <a href="${path}/member/logout.do">로그아웃</a> </c:otherwise> </c:choose> </div> <hr> |
GuestbookController.java
1 2 3 4 | @RequestMapping("/guestbook.do") public String guestbook() { return "guestbook/guestbook"; } |
//방명록, 리스트 페이지
guestbook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <%@ include file="../include/header.jsp" %> <script> $(function(){ //페이지 로딩 완료 gbList(); }); function gbList(){ $.ajax({ url: "${path}/gbList.do", success: function(result){ $("#gbList").html(result); } }); } </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>방명록</h2> <input type="button" value="글쓰기" onclick="location.href='${path}/gbWrite.do'"> <div id="gbList"></div> </body> </html> |
GuestbookController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | @RequestMapping("/gbWrite.do") public String gbWrite() { return "guestbook/gb_write"; } @RequestMapping("/gbList.do") public ModelAndView gbList() { List<GuestbookDTO> items=guestbookDao.getArticleList(); Map<String,Object> map=new HashMap<>(); map.put("list", items); map.put("count", items.size()); return new ModelAndView("guestbook/gb_list", "map", map); } |
result로 값 넘겨주고, gb_list로 포워딩 (gb_list는 guestbook.jsp페이지에 div로 들어가있음)★★★
gb_write.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <%@ include file="../include/header.jsp" %> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>글쓰기</h2> <form name="form1" method="post" action="${path}/gbInsert.do"> <table border="1" width="500px"> <tr> <td>이름</td> <td><input name="name"></td> </tr> <tr> <td>이메일</td> <td><input name="email"></td> </tr> <tr> <td>비밀번호</td> <td><input type="password" name="passwd"></td> </tr> <tr> <td colspan="2"> <textarea rows="5" cols="55" name="content"></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="확인"> <input type="reset" value="취소"> </td> </tr> </table> </form> </body> </html> |
GuestbookController.java [ gbInsert ]
1 2 3 4 5 6 7 | @RequestMapping("/gbInsert.do") public String gbInsert(@ModelAttribute GuestbookDTO dto) { //mongodb에 Document(레코드) 추가 guestbookDao.articleInsert(dto); //페이지 이동(목록 갱신) return "redirect:/guestbook.do"; } |
write.jsp 페이지에서 받아온 form데이터를 @ModelAttribute를 사용하여 dto타입으로 받음
DAO에서는 dto에 날짜정보 저장한 뒤에 insert
gb_list.jsp : guestbook.jsp 하단의 <div id="gbList"></div> 영역에 들어가는 페이지
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../include/header.jsp" %> 게시물수 : ${map.count}건 <c:forEach var="dto" items="${map.list}"> <form method="post" action="${path}/gbEdit.do"> <input type="hidden" name="_id" value="${dto._id}"> <table border="1" style="width:600px;"> <tr align="center"> <td width="20%">이름</td> <td width="30%">${dto.name}</td> <td width="20%">날짜</td> <td width="30%"> <fmt:formatDate value="${dto.post_date}" pattern="yyyy-MM-dd HH:mm:ss"/> </td> </tr> <tr> <td align="center">이메일</td> <td colspan="3">${dto.email}</td> </tr> <tr> <td colspan="4">${dto.content}</td> </tr> <tr> <td colspan="4" align="center"> 비밀번호 <input type="password" name="passwd"> <input type="submit" value="편집"> </td> </tr> </table> </form> </c:forEach> |
[ gbEdit ]//guestbookDao.gbDetail(_id) 호출
1 2 3 4 5 6 7 8 | @RequestMapping("/gbEdit.do") public ModelAndView gbEdit(String _id) { // _id : mongodb의 Document(레코드)의 식별자 GuestbookDTO dto=guestbookDao.gbDetail(_id); Map<String,Object> map=new HashMap<>(); map.put("dto", dto); return new ModelAndView("guestbook/gb_edit","map",map); } |
GuestbookDAOImpl.java
@Override
public GuestbookDTO gbDetail(String _id) {
// findById() 1개의 Document 리턴
// find() Document 리스트 리턴
// findById(_id, 자료형클래스, 컬렉션이름)
return mongoTemplate.findById(_id, GuestbookDTO.class
, COLLECTION_NAME);
}
gd_edit.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <%@ include file="../include/header.jsp" %> <script> function gb_edit(){ document.form1.action="${path}/gbUpdate.do"; document.form1.submit(); } function gb_del(){ if(confirm("삭제하시겠습니까?")){ document.form1.action="${path}/gbDelete.do"; document.form1.submit(); } } </script> </head> <body> <%@ include file="../include/menu.jsp" %> <form method="post" name="form1"> <table border="1" width="500px"> <tr> <td>이름</td> <td><input name="name" value="${map.dto.name}"></td> </tr> <tr> <td>이메일</td> <td><input name="email" value="${map.dto.email}"></td> </tr> <tr> <td>비밀번호</td> <td><input type="password" name="passwd"></td> </tr> <tr> <td colspan="2"> <textarea rows="5" cols="55" name="content">${map.dto.content}</textarea> </td> </tr> <tr> <td colspan="2"> <input type="hidden" name="_id" value="${map.dto._id}"> <input type="button" value="수정" onclick="gb_edit()"> <input type="button" value="삭제" onclick="gb_del()"> <input type="button" value="목록" onclick="location.href='${path}/guestbook.do';"> </td> </tr> </table> </form> </body> </html> |
GuestbookController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | @RequestMapping("/gbUpdate.do") // public String gbUpdate(@ModelAttribute GuestbookDTO dto) { public String gbUpdate(@RequestParam String _id , @RequestParam String name , @RequestParam String email , @RequestParam String content , @RequestParam String passwd) { //System.out.println(dto); //Document(레코드) 수정 GuestbookDTO dto=new GuestbookDTO(); dto.set_id(_id); dto.setName(name); dto.setEmail(email); dto.setContent(content); dto.setPasswd(passwd); guestbookDao.articleUpdate(dto); //목록 페이지로 이동 return "redirect:/guestbook.do"; } @RequestMapping("/gbDelete.do") public String gbDelete(String _id) { //Document(레코드) 삭제 guestbookDao.articleDelete(_id); //목록 페이지로 이동 return "redirect:/guestbook.do"; } } |
[ 실행화면 ]
'Spring > study' 카테고리의 다른 글
spring 30강 Spring Security (0) | 2019.07.16 |
---|---|
Spring Security CSRF (0) | 2019.07.15 |
spring 27강 Spring Boot와 MongboDB 연동 실습(한줄메모장) (0) | 2019.07.11 |
spring 25강 Spring Boot와 Oracle 연동, Thymeleaf Template 적용 (1) | 2019.07.10 |
spring 24강 도로명 주소(daum api) (0) | 2019.07.08 |