spring 27강 Spring Boot와 MongboDB 연동 실습(한줄메모장)
MongoDB는 코딩, 컴파일과 동시에 DB가 생성되기 때문에 DB를 사전 정의할 필요가 없다.
->비정형 데이터에 적합, 유연한 개발 가능
MemoDTO.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.example.spring04.model.memo.dto; import java.util.Date; public class MemoDTO { private String _id; private String writer; private String memo; private Date post_date; ...getter/setter,toString() 생략 ... } |
MemoDAOImpl.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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package com.example.spring04.model.memo.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.memo.dto.MemoDTO; @Repository public class MemoDAOImpl implements MemoDAO { @Autowired MongoTemplate mongoTemplate; String COLLECTION_NAME="memo"; @Override public List<MemoDTO> getMemoList() { //쿼리 객체 Query query=new Query(); //내림차순 정렬 query.with(new Sort(Sort.Direction.DESC, "post_date")); return (List<MemoDTO>)mongoTemplate.find( query, MemoDTO.class, COLLECTION_NAME); } //메모저장 @Override public void memoInsert(MemoDTO dto) { //post_date는 jsp에서 받아오지 않으므로 추가해줌 dto.setPost_date(new Date()); //java.util.Date // insert( 추가할객체, 컬렉션이름 ) mongoTemplate.insert(dto, COLLECTION_NAME); } @Override public MemoDTO memoDetail(String _id) { //레코드 1개를 찾을 경우 findById(_id, 클래스, 테이블이름) return mongoTemplate.findById( _id, MemoDTO.class, COLLECTION_NAME); } @Override public void memoUpdate(MemoDTO dto) { // update 테이블 set 필드=값, 필드=값 where 필드=값 // where 조건 //_id가 dto id와 같은 경우 Query query=new Query(new Criteria("_id").is(dto.get_id())); //수정할 내용 //업데이트 객체 Update update=new Update(); update.set("writer", dto.getWriter()); update.set("memo", dto.getMemo()); // upsert : update or insert mongoTemplate.upsert( query, update, MemoDTO.class, COLLECTION_NAME); } @Override public void memoDelete(String _id) { Query query=new Query(new Criteria("_id").is(_id)); mongoTemplate.remove(query, COLLECTION_NAME); } } |
1 | public <T> List<T> find(Query query, Class<T> entityClass, String collectionName) |
MemoService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.example.spring04.service.memo; import java.util.List; import com.example.spring04.model.memo.dto.MemoDTO; public interface MemoService { List<MemoDTO> getMemoList(); //메모 목록 void memoInsert(MemoDTO dto); //메모 저장 MemoDTO memoDetail(String _id); //상세내용 void memoUpdate(MemoDTO dto); // 수정 void memoDelete(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> |
MemoConroller.java
1 2 3 4 | @RequestMapping("/memo.do") public String memo() { return "memo/memo"; } |
memo.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 | <%@ 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(){ memo_list(); $("#btnWrite").click(function(){ memo_insert(); }); }); function memo_insert(){ var writer=$("#writer").val(); var memo=$("#memo").val(); $.ajax({ type: "post", data: {"writer":writer, "memo":memo}, url: "${path}/memo_insert.do", success: function(){ memo_list(); //목록 갱신 $("#writer").val(""); $("#memo").val(""); } }); } function memo_list(){//목록 갱신 $.ajax({ //화면없이 백그라운드에서 실행되는 코드 url: "${path}/memo_list.do", success: function(result){ $("#memoList").html(result); } }); } function memo_view(num){ // memo_view.do?_id=5 location.href="${path}/memo_view.do?_id="+num; } </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>한줄메모장</h2> 이름 : <input id="writer"> 메모 : <input id="memo" size="50"> <input type="button" value="확인" id="btnWrite"> <div id="memoList"></div> </body> </html> |
MemoConroller.java
1 2 3 4 5 6 7 8 | //메모 @RequestMapping("/memo_list.do") public ModelAndView memo_list() { Map<String,Object> map=new HashMap<>(); List<MemoDTO> list=memoService.getMemoList(); map.put("items", list); return new ModelAndView("memo/memo_list", "map", map); } |
memo_list.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 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <table border="1" width="700px"> <tr> <th>No</th> <th>이름</th> <th>메모</th> <th>날짜</th> </tr> <c:forEach var="row" items="${map.items}" varStatus="status"> <tr> <td>${status.count}</td> <!-- index 0부터, count 1부터 --> <td>${row.writer}</td> <td> <a href="#" onclick="memo_view('${row._id}')"> ${row.memo}</a> </td> // 포맷설정 안해주면 세계표준 형식으로 출력된다 <td><fmt:formatDate value="${row.post_date}" pattern="yyyy-MM-dd HH:mm:ss" /></td> </tr> </c:forEach> </table> |
varStatus를 사용해서 목록수나 목록의 현재 index, count 등의 위치값을 사용
${row._id}를 사용하면 키값으로 임의의 숫자를 주기때문에 1.0으로 출력된다.
varStatus 속성으로 변수를 지정하면 index, count 등 목록의 현재 위치값을 얻을 수 있다.
memo_view.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 | <%@ 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(){ $("#btnUpdate").click(function(){ document.form1.action="${path}/memo_update.do"; document.form1.submit(); }); $("#btnDelete").click(function(){ if(confirm("삭제하시겠습니까?")){ document.form1.action="${path}/memo_delete.do"; document.form1.submit(); } }); }); </script> </head> <body> <%@ include file="../include/menu.jsp" %> <h2>메모장</h2> <form name="form1" method="post"> <input type="hidden" name="_id" value="${dto._id}"> 이름 <input name="writer" value="${dto.writer}"><br> 메모 <input name="memo" value="${dto.memo}" size="50"><br> <input type="button" value="수정" id="btnUpdate"> <input type="button" value="삭제" id="btnDelete"> <input type="button" value="목록" id="btnList" onclick="location.href='${path}/memo.do'"> </form> </body> </html> |
MemoConroller.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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | package com.example.spring04.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.example.spring04.model.memo.dto.MemoDTO; import com.example.spring04.service.memo.MemoService; @Controller public class MemoController { @Autowired // @Inject MemoService memoService; @RequestMapping("/memo.do") public String memo() { return "memo/memo"; } //메모 @RequestMapping("/memo_list.do") public ModelAndView memo_list() { Map<String,Object> map=new HashMap<>(); List<MemoDTO> list=memoService.getMemoList(); map.put("items", list); return new ModelAndView("memo/memo_list", "map", map); } @RequestMapping("/memo_insert.do") public String memo_insert(@ModelAttribute MemoDTO dto) { memoService.memoInsert(dto); return "redirect:/memo.do"; } @RequestMapping("/memo_view.do") public ModelAndView memo_view(String _id) { MemoDTO dto=memoService.memoDetail(_id); return new ModelAndView("memo/memo_view", "dto", dto); } @RequestMapping("/memo_update.do") public String memo_update(@ModelAttribute MemoDTO dto) { memoService.memoUpdate(dto); return "redirect:/memo.do"; } @RequestMapping("/memo_delete.do") public String memo_delete(String _id) { memoService.memoDelete(_id); return "redirect:/memo.do"; } } |
'Spring > study' 카테고리의 다른 글
Spring Security CSRF (0) | 2019.07.15 |
---|---|
spring 28강 Spring Boot와 MongboDB 연동 실습(방명록) (0) | 2019.07.12 |
spring 25강 Spring Boot와 Oracle 연동, Thymeleaf Template 적용 (1) | 2019.07.10 |
spring 24강 도로명 주소(daum api) (0) | 2019.07.08 |
spring 23강 게시판 만들기4( 게시물 수정 ) (0) | 2019.07.08 |