porm.xml 에 추가 (아래에있음)

http://mvnrepository.com/

MongoDB Java Driver

Spring Data MongoDB Core



프로젝트 새로 생성시

Maven-> update project 해주어야함.





jsp 파일 생성시 자동추가되도록 설정 

<!DOCTYPE html>

<%@ 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="spring" uri="http://www.springframework.org/tags"%>

<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head> 
<body>

</body>
</html>




몽고디비 설정


> use myperson
switched to db myperson
> db.createCollection("dto")
{ "ok" : 1 }
> show collections
dto
person
> show dbs
admin     0.000GB
config    0.000GB
local     0.000GB
myperson  0.000GB

>data={ "_id" : 1, "name" : "김연아", "hp" : "0102-222-3333", "address" : "서울시 강남구", "age" : 26 }
> db.dto.find()
> db.dto.insert(data)
WriteResult({ "nInserted" : 1 })
> db.dto.find()
{ "_id" : 1, "name" : "김연아", "hp" : "0102-222-3333", "address" : "서울시 강남구", "age" : 26 }
>







porm.xml


Spring 버전 변경


<!-- Spring -->

<spring-framework.version>4.0.9.RELEASE</spring-framework.version>



#몽고DB Core

<dependency>

    <groupId>org.springframework.data</groupId>

    <artifactId>spring-data-mongodb</artifactId>

    <version>1.6.1.RELEASE</version>

</dependency>



#몽고DBJAVA드라이버

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>mongo-java-driver</artifactId>

    <version>2.11.4</version>

</dependency>



web.xml 인코딩 문제


    <filter>

    <filter-name>encodingFilter</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <init-param>

      <param-name>encoding</param-name>

      <param-value>UTF-8</param-value>

    </init-param>

    </filter>

  <filter-mapping>

    <filter-name>encodingFilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

    



제일아래쪽 servlet

    <servlet-mapping>

        <servlet-name>dispatcherServlet</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>



src/main/java 

test.mongodb 패키지 생성




mvc-config

    <context:annotation-config></context:annotation-config>

    <context:component-scan base-package="test.*"></context:component-scan>





application-config

**namespace 에서 mongo 추가


<!--  mongo db server setting -->

<mongo:mongo id="mongo" host="127.0.0.1" port="27017">

<mongo:options

threads-allowed-to-block-for-connection-multiplier="4"

connect-timeout="1000" 

max-wait-time="1500"

auto-connect-retry="true"

socket-keep-alive="true"

socket-timeout="1500"

write-number="1"

write-timeout="0"

write-fsync="true"

/>

</mongo:mongo>



<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="databaseName" value="myperson"/>
<constructor-arg name="mongo" ref="mongo"/>
<!-- 보안설정 -->
<constructor-arg name="userCredentials">
<bean class="org.springframework.data.authentication.UserCredentials">
<constructor-arg name="username" value="admin"/>
<constructor-arg name="password" value=""/>
</bean>
</constructor-arg>
<property name="writeConcern" value="SAFE"/>
</bean>
<!-- test.* 으로해도됨 -->
<mongo:repositories base-package="test.mongodb"/>





src/main/java
test.mongodb 밑에
UserDto.java 생성

import org.springframework.data.annotation.Id;       <- @Id 추가시 해당 패키지




@Document(collection="dto")
public class UserDto

@Id
private String id;
private String name;
private String hp;
private String address;
private int age;

후 setter getter 해서 자동생성



최종 UserDto.java 파일 

package test.mongodb;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="dto")
public class UserDto {
@Id
private String id;
private String name;
private String hp;
private String address;
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHp() {
return hp;
}
public void setHp(String hp) {
this.hp = hp;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}






src/main/java
test.mongodb 패키지 밑에 생성
ListController.java                  -> 리스트 출력
UpdateController.java                -> 정보수정
Userdao.java                         -> 쿼리문수행
WriteController.java                 -> 새글 추가
DeleteController.java                -> 삭제 
 
webapp/WEB-INF/view 에 jsp 생성
boardlist.jsp                        ->게시글 리스트
showMessage.jsp                      ->
updateform.jsp                       -> 수정버튼시 불러오는 폼
writeform.jsp                        -> 새글추가시 불러오는 폼







index.jsp body부분 에 삽입 (메인페이지 접속시 list.do 로 연결되도록함)

<c:redirect url="mongo/list.do"/>






test.mongodb/ListController.java


@Controller

public class ListController {

@RequestMapping("/mongo/list.do")

public ModelAndView list()

{

ModelAndView model=new ModelAndView();

model.setViewName("boardlist");

return model;

}

}







초기 셋팅








src/main/java/test.mongodb/Userdao.java


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;

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.stereotype.Repository;



@Repository

public class Userdao {

@Autowired

private MongoTemplate mongoTemp;

public void dropCollection()

{

mongoTemp.dropCollection(UserDao.class);

}

public List<UserDto> findList()

{

//방법 1 : 전체 데이타를 목록으로 얻고자 할 경우

List<UserDto> list=mongoTemp.findAll(UserDto.class,"dto");

//방법 2 - 조건에 의한 목록을 얻고자 할경우

/* Query query=new Query(Criteria.where("_id").in("a1","a2","a3"));

List<UserDto> list=mongoTemp.find(query, UserDto.class);*/

return list;

}

}





ListController


@Autowired

private Userdao dao;


List<UserDto> list=dao.findList();

model.addObject("list",list);

model.addObject("count",list.size());



추가






boardlist 

부트스트랩 추가 head 에


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>





body 부분에 추가

<body>
<c:if test="${count==0}">
<b>저장된 데이타가 없습니다</b>
</c:if>
<c:if test="${count>0}">
<b>총 <span style="color: red;">${count}</span>개의 데이타가 있습니다.</b>
</c:if>
</body>





디자인부분 추가



<input type="button" class="btn btn-sm btn-success" value="멤버등록" onclick="location.href='writeform.do'" style="magin-left:50px;">

<table style="margin:0 auto;" class="table table-striped">

<caption><b>MongoDB Test</b></caption>

<tr bgcolor="#ffffcc">

<th style="text-align: center;">순번</th>

<th style="text-align: center;">이름</th>

<th style="text-align: center;">핸드폰</th>

<th style="text-align: center;">주소</th>

<th style="text-align: center;">나이</th>

<th style="text-align: center;">편집</th>

</tr>

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

<tr>

<td align="center">${i.count}</td>

<td align="center">${dto.name}</td>

<td align="center">${dto.hp}</td>

<td align="center">${dto.address}</td>

<td align="center">${dto.age}</td>

<td align="center">

<!-- info 파란색 버튼 danger 빨간색 버튼 -->

<input type="button" value="수정" class="btn btn-cs btn-info" 

onclick="location.href='updateform.do?name=${dto.name}'">

<input type="button" value="삭제" class="btn btn-cs btn-danger" 

onclick="location.href='delete.do?name=${dto.name}'">

</td>

</tr>

</c:forEach>

</table>

</body>




webapp/index.jsp


body 내용을 수정 list.do 로 표출되도록 




<c:redirect url="mongo/list.do"></c:redirect>






여기까지 진행하였을경우 프로젝트 실행시 정상적으로 입력된 게시글들이 출력되어야함. 







WriteController.java


@Controller

public class WriteController {

@Autowired

private UserDao dao;

@RequestMapping("/mongo/writeform.do")

public String form()

{

return "writeform";

}

}






Writeform.jps


<head>
<meta charset="utf-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head> 
<body>
<form action="write.do" method="post">
<table class="table table-bordered" style="width:300px; margin: 0 auto;">
<caption><b>맴버 등록하기</b></caption>
<tr>
<th style="width:100px;">이름</th>
<td>
<input type="text" name="name" autofocus="autofocus" required="required">
</td>
</tr>
<tr>
<th style="width:100px;">핸드폰</th>
<td>
<input type="text" name="hp" required="required">
</td>
</tr>
<tr>
<th style="width:100px;">주소</th>
<td>
<input type="text" name="address" required="required">
</td>
</tr>
<tr>
<th style="width:100px;">나이</th>
<td>
<input type="text" name="age" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="mongodb저장" class="btn btn-sm btn-warning">
<input type="button" value="멤버목록" class="btn btn-sm btn-success" onclick="location.href='list.do'">
</td>
</tr>
</table>
</form>
</body>






UserDao.java   추가



//dto 한개 저장시

public void insert(UserDto dto)

{

mongoTemp.insert(dto);

}

//dto 여러개를 List 에 담아 저장시 

public void insertList(List<UserDto> list)

{

mongoTemp.insert(list,UserDto.class);

}








WriteController



@RequestMapping("/mongo/write.do")

public String readData(@ModelAttribute UserDto dto)

{

dao.insert(dto);

return "redirect:list.do";

}



여기까지 진행하면 맴버등록이 됨.











boardlist.jsp

네임클릭시 반응하게 네임부분 수정 



<td align="center">

<a href="content.do?name=${dto.name}">${dto.name}</a>

</td>






/WEB-INF/view/content.jsp 생성




UserDao.java 추가 

public UserDto getSearchName(String name)

{

Query query=new Query(Criteria.where("name").is(name));

return mongoTemp.findOne(query, UserDto.class);

}





ListController.java 추가

@RequestMapping("/mongo/content.do")

public ModelAndView content(@RequestParam String name)

{

ModelAndView model=new ModelAndView();

UserDto dto=dao.getSearchName(name);

model.addObject("dto",dto);

model.setViewName("content");

return model;

}




Content.jsp -> writeform 에 있는거 그대로 복사해서 수정


form 삭제후


<body>


<table class="table table-bordered" style="width:300px; margin: 0 auto;">

<caption><b>맴버 확인</b></caption>

<tr>

<th style="width:100px;">이름</th>

<td>

${dto.name}

</td>

</tr>

<tr>

<th style="width:100px;">핸드폰</th>

<td>

${dto.hp}

</td>

</tr>

<tr>

<th style="width:100px;">주소</th>

<td>

${dto.address}

</td>

</tr>

<tr>

<th style="width:100px;">나이</th>

<td>

${dto.age}세

</td>

</tr>

<tr>

<td colspan="2" align="center">


<input type="button" value="멤버목록" class="btn btn-sm btn-success" onclick="location.href='list.do'">

</td>

</tr>

</table>


</body>




여기까지 이상없이 진행시 

---이름 수정 누르면 데이터 출력--






삭제기능추가


UserDao.java


public void deletedata(String name)

{

Query query=new Query(Criteria.where("name").is(name));

mongoTemp.remove(query,UserDto.class);

}




deleteController.java


@Controller

public class DeleteController {


@Autowired

private UserDao dao;

@RequestMapping("mongo/delete.do")

public String delete(@RequestParam String name)

{

dao.deletedata(name);

return "redirect:list.do";

}

}





여기까지 진행시 삭제버튼누르면 해당 이름 삭제됨.



수정기능


writeform.jsp 내용을 updateform.jsp 로 복사


updateform.jsp


<body>

<form action="update.do" method="post">

<table class="table table-bordered" style="width:300px; margin: 0 auto;">

<caption><b>맴버 정보수정하기</b></caption>

<tr>

<th style="width:100px;">이름</th>

<td>

${dto.name }

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

</td>

</tr>

<tr>

<th style="width:100px;">핸드폰</th>

<td>

<input type="text" name="hp" required="required" value="${dto.hp}">

</td>

</tr>

<tr>

<th style="width:100px;">주소</th>

<td>

<input type="text" name="address" required="required" value="${dto.address}">

</td>

</tr>

<tr>

<th style="width:100px;">나이</th>

<td>

<input type="text" name="age" required="required" value="${dto.age}">

</td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" value="mongodb수정" class="btn btn-sm btn-warning">

<input type="button" value="멤버목록" class="btn btn-sm btn-success" onclick="location.href='list.do'">

</td>

</tr>

</table>

</form>

</body>




updateController.java



@Controller

public class UpdateController {


@Autowired

private UserDao dao;

@RequestMapping("/mongo/updateform.do")

public ModelAndView updateform(@RequestParam String name)

{

ModelAndView model=new ModelAndView();

UserDto dto=dao.getSearchName(name);

model.addObject("dto",dto);

model.setViewName("updateform");

return model;

}

}



-----------------------여기까지 했을때 수정폼 나오면 정상



Userdao.java


public void updateData(UserDto dto)

{

Query query=new Query(Criteria.where("name").is(dto.getName()));

mongoTemp.updateFirst(query, Update.update("hp", dto.getHp()), UserDto.class);

mongoTemp.updateFirst(query, Update.update("address", dto.getAddress()), UserDto.class);

mongoTemp.updateFirst(query, Update.update("age", dto.getAge()), UserDto.class);

}




updateController.java


@RequestMapping("/mongo/update.do")

public String update(@ModelAttribute UserDto dto)

{

dao.updateData(dto);

return "redirect:list.do";

}



+ Recent posts