Spring Boot와 MongoDB 연동해서 회원관리 예제 (회원가입, 로그인, 로그아웃)

Back-End/Spring 2019. 7. 8. 17:36

실습예제 (기본설정)


회원가입, 로그인, 로그아웃


이번에는 타임리프 템플릿을 사용하지 않고 view를 jsp로 사용할 예정


1)   프로젝트 생성 : Spring Starter Project


프로젝트 이름 : spring04_mongodb


Package : com.example.spring04



2)  pom.xml

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.example</groupId>
    <artifactId>spring04_mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>spring04_mongodb</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath /<!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>

        <!-- spring boot auto restart
        (설정, 클래스가 바뀌면 auto restart) -->
        <!-- 스프링부트에서는 소스코드가 바뀌어도 자동으로 서버가 재시작하지 않기 때문에 이 구문을 추가해서 자동으로 재시작하게 해준다. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        
        <!-- mybatis와 스프링 연동 라이브러리 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <!-- 스프링 부트 라이브러리 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        
        <!-- MYSQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        
        <!-- Mogno DB -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- 이번 프로젝트에서는 jsp를 사용할 예정이기 때문에 이 코드를 추가해주었다. -->
        <!-- JSP / JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

<!--내장형 톰캣을 사용하기 때문에 적는 구문 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>
    
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
cs



Spring04MongodbApplication.java (스프링부트 프로젝트가 시작되는 메인메소드가 있는 파일)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example.spring04;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication //스프링부트 시작 어노테이션
public class Spring04MongodbApplication {
 
    //메인메소드 이 java파일에서 프로젝트가 실행이된다.
    public static void main(String[] args) {
        SpringApplication.run(Spring04MongodbApplication.class, args);
    }
}
 
cs



application.properties

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
server.port = 80
##톰캣포트는 다른 포트번호와 겹치지 않게 써야한다.##
 
## View Path Config ## #jsp를 쓰기위한 mvc설정 (prefix와 suffix)#
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
 
#jsp auto restart
#jsp 페이지의 소스가 바뀌면 자동으로 서버가 다시시작되게끔 하는 코드#
server.servlet.jsp.init-parameters.development=true
spring.devtools.livereload.enabled=true
 
# static resource
#리소스 파일 (css,js)등의 경로#
spring.mvc.static-path-pattern=/res/**
 
# custom error page
#에러가 발생했을 경우 내가 만든 에러페이지를 보여줄 것인가에 대한 옵션#
server.error.whitelabel.enabled=false
 
## MongoDB Config ##
#MongoDB의 포트번호, 데이터베이스 이름, 계정아이디, 비밀번호#
spring.data.mongodb.uri=mongodb://localhost:27017 
spring.data.mongodb.database=web
spring.data.mongodb.username=web
spring.data.mongodb.password=1234
cs



MongoConfig.java (application.properties에서 설정한 MongoDB에 정보를 읽어서 Bean을 생성하는 페이지)

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
package com.example.spring04.config;
 
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
 
//application.properties에서 설정한 MongoDB에 정보를 읽어서 Bean을 생성하는 페이지
 
//스프링 부트에서는 servlet-context, root-context가 없기 때문에 
 
@Configuration //Configuration 어노테이션은 root-context안에 들어갈 코드를 어노테이션으로 만든것이라고 생각하면 된다.
 
public class MongoConfig extends AbstractMongoConfiguration {
    
    @Value("${spring.data.mongodb.username}")     //application.properties에서 정의한 MongoDB에 계정 아이디
    private String userName;
    
    
    @Value("${spring.data.mongodb.password}")    //application.properties에서 정의한 MongoDB에 계정 비밀번호
    private String password;
    
    
    @Value("${spring.data.mongodb.database}"//application.properties에서 정의한 MongoDB에있는 데이터베이스
    private String database;
 
    
    @Override
    protected String getDatabaseName() {
        return database;
    }
    
    //레거시 프로젝트에서 xml파일 안에 <bean>태그 안에 있던 코드를 적어놓은것.
    //mongotemplate을 만들어서 리턴해준다.
    public @Bean MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate((MongoClient) mongoClient(), database);
    }
 
    @Override
    public MongoClient mongoClient() {
        MongoCredential credential =  //인증 정보
                MongoCredential.createCredential(
                        userName, database, password.toCharArray()); //아이디, 데이터베이스, 비밀번호 
        return new MongoClient(new ServerAddress("localhost"27017), 
                Arrays.asList(credential));
    }
}
cs



HomeController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.example.spring04.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller //컨트롤러 빈으로 등록

public class HomeController {
    // http://localhost까지만 나온다는 뜻, 시작페이지
    @RequestMapping("/")
    
    public String home() {
        // /WEB-INF/view/home.jsp
        return "home";  // home.jsp로 포워딩
        //home.jsp페이지가 출력된다.
    }
}
cs



- jsp를 view로 사용하는 방법 -


jsp를 사용하기 위해서는 추가 작업이 필요하다.



1. src/main 하위에 디렉토리 추가



src/main/webapp


src/main/webapp/WEB-INF


src/main/webapp/WEB-INF/views





2. application.properties 설정



3. pom.xml에서 thymeleaf 라이브러리를 주석처리 한다.



home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ 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" %>
<h1>Welcome!</h1>
</body>
</html>
cs



header.jsp

(스프링부트에서는 jsp를 제외한 것들을 서블릿으로 인식하기 때문에 리소스경로를 지정해야 한다)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
 <!-- core, fmt, functions, jquery, css가 실행될 수 있게끔 포함시킨 header.jsp 페이지 -->
    
<%@ taglib prefix="c" 
uri="http://java.sun.com/jsp/jstl/core" %>
 
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
 
<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
 
<script src="http://code.jquery.com/jquery-3.2.1.js"></script>
<link rel="stylesheet" href="/res/css/style.css">
cs



style.css

1
2
3
4
5
6
7
<!--하이퍼링크에 대한 스타일을 지정 -->
@CHARSET "UTF-8";
a:link { text-decoration: none; color: blue; }
a:hover { text-decoration: underline; color: red; }
a:visited { text-decoration: none; }
a:active { text-decoration: none; color: yellow; }
cs



메모장과 방명록을 MongoDB로 구현할 예정



menu.jsp (view)

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"%>
<%@ taglib prefix="c" 
uri="http://java.sun.com/jsp/jstl/core" %>
 
<!-- HOME, 메모장, 방명록페이지로 가는 링크를 추가 -->
<a href="${path}/">Home</a> | 
<a href="${path}/memo.do">메모장</a> | 
<a href="${path}/guestbook.do">방명록</a> | 
<div style="text-align:right;">
    
    <c:choose>
    <!-- 세션에 저장된 유저의 아이디가 NULL이면 로그인페이지로 이동 -->
    <c:when test="${sessionScope.userid == null }">
    
    <!-- 로그인 페이지로 이동하는 링크 -->
    <a href="${path}/member/login.do">로그인</a>
    </c:when>
    
    <c:otherwise>
        <!-- 세션에 저장된 유저의 아이디가 NULL이 아니라면 로그인 중이라는 메시지를 출력한다. -->
        ${sessionScope.name}님이 로그인중입니다.
        
        <!-- 로그인중이므로 로그아웃 할 수 있는 링크를 추가한다. -->
        <a href="${path}/member/logout.do">로그아웃</a>
        
    </c:otherwise>
</c:choose>    
</div>  
<hr>
cs



회원관리 (회원가입, 로그인, 로그아웃)


MongoDB에서는 PK(기본키) 가 _id로 고정되어 있다.


그렇기 때문에 DTO를 만들때 필드이름을 _id로 해주어야 한다.



================================== 로그인 ==================================



MemberDTO.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
package com.example.spring04.model.member.dto;
 
public class MemberDTO {
    
    private String _id;//mongodb의 Document(레코드에 해당)식별자
    private String passwd;
    private String name;    
    private String email;    
    private String hp;        
    private String zipcode;    
    private String address1;
    private String address2;
    
    //생성자,getter,setter,toString()
    public MemberDTO() {
    }
    public String get_id() {
        return _id;
    }
    public void set_id(String _id) {
        this._id = _id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    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 getHp() {
        return hp;
    }
    public void setHp(String hp) {
        this.hp = hp;
    }
    public String getZipcode() {
        return zipcode;
    }
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
    public String getAddress1() {
        return address1;
    }
    public void setAddress1(String address1) {
        this.address1 = address1;
    }
    public String getAddress2() {
        return address2;
    }
    public void setAddress2(String address2) {
        this.address2 = address2;
    }
    @Override
    public String toString() {
        return "MemberDTO [_id=" + _id + ", passwd=" + passwd + ", name=" + name + ", email=" + email + ", hp=" + hp
                + ", zipcode=" + zipcode + ", address1=" + address1 + ", address2=" + address2 + "]";
    }
    
}
 
cs



MemberDAO.java 생성

1
2
3
4
5
6
7
8
9
package com.example.spring04.model.member.dao;
 
import com.example.spring04.model.member.dto.MemberDTO;
 
public interface MemberDAO {
    MemberDTO loginCheck(String userid, String passwd); //로그인 체크 메소드
    void join(MemberDTO dto);  //회원 가입처리 함수
}
 
cs



MemberDAOImpl.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
package com.example.spring04.model.member.dao;
 
import java.util.List;
 
import javax.inject.Inject;
 
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;
 
import com.example.spring04.model.member.dto.MemberDTO;

@Repository 
//DAO에서 사용하는 어노테이션, Component도 사용가능하다.
//sql을 쓸 수 없으므로 함수를 사용해서 명령을 표현

public class MemberDAOImpl implements MemberDAO {
 
    //mongodb에 접속하여 명령어를 실행하는 객체
    //Autowired 대신에 inject를 써도 된다.
    //Inject를 사용하려면 pom.xml에 라이브러리를 추가해 주어야 한다.
    //Inject 어노테이션을 쓰고 우클릭 후 fix Project Setup을 누르고 jar파일에대고
    //ok를 누르면 Inject를 사용할 수 있다.
    //의존성 주입
    @Inject
    //@Autowired
    private MongoTemplate mongoTemplate;
    //bean에 MongoTemplate을 리턴하는 메소드가 있었는데 이 메소드가 실행되어야
    //Mongo DB를 사용할 수 있기 때문에 의존관계를 주입시키는 것이다.
    //템플릿을 사용하기 위한 의존성 주입


    //mongodb의 컬렉션(테이블에 해당)
    //그리고 레코드 대신 도큐먼트(document)라고 부르고 사용한다.
    String COLLECTION_NAME="member";
    

    //로그인 체크    
    @Override
    public MemberDTO loginCheck(String userid, String passwd) {
        // _id : Document(레코드에 해당)의 식별자
        Query query=new Query(new Criteria("_id").is(userid)//키값 (_id)가 userid와 같고,
                .and("passwd").is(passwd)); //passwd와 passwd(입력한값)이 같은지 확인
//mongoTemplate.find(쿼리, 리턴자료형, 컬렉션이름)
//리스트가 리턴되므로 get(0) 첫번째 Document만 리턴        
        List<MemberDTO> list=mongoTemplate.find(query
                , MemberDTO.class,COLLECTION_NAME); 
        //COLLECTION_NAME는 테이블이름이고, 위의 결과가 참이되면
        //DTO에다 아이디와 비밀번호를 저장한다.
        
        //만약 list가 0보다 크면 1개만 출력되고 아니면 null이 출력된다.
        if(list.size() > 0) {
            return list.get(0);
        }else {
            return null;
        }
    }
    
    //회원가입 처리
    //insert쿼리라고 생각하면 된다.
    @Override
    public void join(MemberDTO dto) {
        //Document가 생성됨(insert)
        //dto안에 들어있는 값을 COLLECTION_NAME 컬렉션(테이블)에 저장한다는 의미
        mongoTemplate.insert(dto, COLLECTION_NAME);       
    }
}
cs



MemberService.java

1
2
3
4
5
6
7
8
9
10
package com.example.spring04.service.member;
 
import com.example.spring04.model.member.dto.MemberDTO;
 
public interface MemberService {
    MemberDTO loginCheck(String userid, String passwd);
    void join(MemberDTO dto);
    //dao를 호출하기위한 메소드
}    
 
cs



MemberServiceImpl.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
package com.example.spring04.service.member;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.example.spring04.model.member.dao.MemberDAO;
import com.example.spring04.model.member.dto.MemberDTO;
 
@Component //빈에 등록
public class MemberServiceImpl implements MemberService {
 
    @Autowired //의존성 주입
    private MemberDAO memberDao;
    
    @Override
    public MemberDTO loginCheck(String userid, String passwd) {
        return memberDao.loginCheck(userid, passwd);
    }
    @Override
    public void join(MemberDTO dto) {
        memberDao.join(dto);
    }
}
 
cs



MemberController.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
package com.example.spring04.controller;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.example.spring04.model.member.dto.MemberDTO;
import com.example.spring04.service.member.MemberService;
 
@Controller //컨트롤러 빈으로 설정
@RequestMapping("/member/*"//공통적인 URL 매핑
public class MemberController {
    
    @Autowired //의존성주입 (스프링프레임워크에서 지원하는 어노테이션)
    private MemberService memberService;
    
    @RequestMapping("login.do"//세부적인 매핑
    public ModelAndView login() {
        return new ModelAndView("member/login"); //login.jsp로 이동
    }
cs



home.jsp (view)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ 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" %>
<h1>Welcome!</h1>
<c:if test="${sessionScope.userid != null}">
<!-- 만약 세션에 유저의 아이디가 저장되어 있으면 방문을 환영한다는 메시지 출력 -->
    <h2>${sessionScope.name}(${sessionScope.userid})님의
        방문을 환영합니다.
    </h2>
</c:if>
</body>
</html>
cs



login.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
57
58
59
60
61
<%@ 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>로그인 페이지</title>
 
<!-- 로그인 페이지 -->
<%@ include file="../include/header.jsp" %>
<script>
$(function(){
 
 
    //밑에 있는 id가 #btnLogin으로 맵핑되는 함수, 클릭 버튼을 누르면 컨트롤러에 있는 login_check.do로 form1에 저장된 자료를 넘긴다.
    $("#btnLogin").click(function(){
        $("#form1").attr("action","/member/login_check.do");
        $("#form1").submit();
    });
 
 
    //밑에 있는 id가 #btnJoin으로 맵핑되는 함수, 클릭 버튼을 누르면 컨트롤러에 있는 join.do라는 새로운 페이지로 이동시킨다.
//컨트롤러의 join.do로 이동했다가 회원가입페이지로 이동할 예정
    $("#btnJoin").click(function(){
        $(location).attr("href","/member/join.do")    
    });
});
 
</script>
</head>
<body>
<%@ include file="../include/menu.jsp" %>
<h2>로그인하세요</h2>
 
<form name ="form1" id="form1" method="post">
<table border="1" style="width: 400px">    
 
    <tr>
        <td>아이디</td>
        <td><input type="text" name="_id" id = "_id" /></td>
        <!-- 데이터베이스에 아이디가 _id로 되어있기 때문에 _id로 한다. -->
    </tr>
    <tr>
        <td>비밀번호</td>
        <td><input type="password" name="passwd" id = "passwd" /></td>
            <font color="red">${map.message}</font></td>
<!--비밀번호가 틀렸을때 되돌아와서 표시할 메시지-->
        <!-- 비밀번호의 타입을 password로 하고 이름을 passwd로 한다. -->
    </tr>
    <tr>
        <td colspan="2" align="center">    
            <input type="button" id="btnLogin" value="로그인" />
            <!-- 로그인을 버튼을  누르면 id값이 위쪽에 있는 스크립트에 맵핑된다.->
            
            <input type="button" id="btnJoin" value="회원가입" /></td>
            <!--회원가입 버튼을 누르면 id값이 위쪽에 있는 스크립트에 맵핑된다.-->
 
        </td>
    </tr>
</table>
</form>
</body>
</html>
cs



================================== 회원가입 ==================================


MemberController.java 중 일부

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    @RequestMapping("join.do")
    public String join() {
        return "member/join"
        //join.jsp 회원가입페이지로 이동
    }
 
    
    //회원가입페이지에서 회원가입 내용을 다 작성한뒤 버튼을 누르면 맵핑되는 메소드
    //dto에 회원정보를 저장하고, Service에 값을 전달함
 
    @RequestMapping("member_join.do")
    public String member_join(String _id, String passwd
            , String name) {
        MemberDTO dto=new MemberDTO();
        dto.set_id(_id);
        dto.setPasswd(passwd);
        dto.setName(name);
        memberService.join(dto); //mongodb에 insert됨
        return "redirect:/member/login.do"//로그인 화면으로 이동
    }
cs



join.jsp (회원가입 페이지)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ 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>
<!-- 유저의 아이디와 비밀번호, 이름을 작성하고 확인 버튼을 누르면 컨트롤러의 member_join.do로 맵핑된다. -->
<form method="post" action="${path}/member/member_join.do">
아이디 : <input name="_id"><br>
비번 : <input type="password" name="passwd"><br>
이름 : <input name="name"><br>
<input type="submit" value="확인">
</form>
</body>
</html>
cs



MemberServiceImpl.java

1
2
3
4
    @Override
    public void join(MemberDTO dto) {
//회원가입 메소드
        memberDao.join(dto);
    }
cs



MemberDAOImpl.java

1
2
3
4
5
6
    
//회원가입 처리
    @Override
    public void join(MemberDTO dto) {
        //Document가 생성됨(insert)
//mongoDB에 member이라는 컬렉션에 사용자가 입력한 값이 들어가게 된다.
        mongoTemplate.insert(dto, COLLECTION_NAME);
    }

cs



================================== 로그아웃 ==================================


view에서 로그아웃 버튼을 누르면 컨트롤러로 맵핑되어서 세션정보를 초기화하고 다시 로그인 페이지로 이동한다.


MemberController.java

1
2
3
4
5
6
7
8
9
10
    
    @RequestMapping("logout.do")
    public String logout(HttpSession session) {
 
        //세션 정보 초기화
        session.invalidate();
 
        //로그인 페이지로 이동
        return "redirect:/member/login.do";
    }
cs



: