본문 바로가기
매일코딩/Spring

18.스프링프로젝트 - 메뉴바(구버전) 방명록 조회 수정 삭제

by 인생여희 2016. 11. 1.
반응형

- 방명록 테이블 







0. 방명록 DTO


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
package com.example.web03.model.guestbook.dto;
 
import java.sql.Date;
 
public class GuestbookDTO {
 
 
    private int idx;
    private String name;
    private String email;
    private String passwd;
    private String content;
    private Date post_date;
 
 
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    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 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 Date getPost_date() {
        return post_date;
    }
    public void setPost_date(Date post_date) {
        this.post_date = post_date;
    }
    
    @Override
    public String toString() {
        return "GuestbookDTO [idx=" + idx + ", name=" + name + ", passwd=" + passwd + ", content=" + content
                + ", post_date=" + post_date + "]";
    }
    
    
    
}
 
cs


1. 메뉴바 


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"%>
 
<!-- core tag 선언문 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<!-- set var ="변수명" value="값"
pageContext.request.contextPath
컨텍스트 이름을 리턴(request.getContextPath()와 같음) -->
 
<c:set var="path" value="${pageContext.request.contextPath}"></c:set>
 
<!-- 상단메뉴 구성 -->
 
<div style="text-align: center;">
<a href="${path}/guestbook/list">방명록</a>
 
<a href="${path}/memo/list">한줄메모장</a>
 
<a href="${path}/shop/product_list">상품관리</a>
 
<c:if test="${sessionScope.id!=null }">
 
<a href="${path}/shop/cart_list">장바구니</a>
 
</c:if>
 
<a href="${path}/board/board_list.do">게시판</a>
 
 
 
 
<c:choose>
    <c:when test="${sessionScope.id==null }">
    <!-- 세션변수 id 값이 없을때 -->
    <a href="${path}/member/login">로그인</a>
    <a href="/web03/member/memberInsert">회원가입</a>
    </c:when>
    
    <c:otherwise>
        <!-- 세션 변수 id 값이 있을때 -->
        
    [  ${sessionScope.id}님 로그인 중 ]
    <a href="${path}/member/logout">로그아웃</a>
    <a href="${path}/member/member_info.do">회원정보 수정</a>
    </c:otherwise>
    
</c:choose>
 
 
<h2 align="center">${message}</h2>
</div>
 
 
cs



2. 방명록 컨트롤러 


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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.example.web03.controller.guestbook;
 
import java.util.List;
 
import javax.inject.Inject;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.example.web03.model.guestbook.dao.GuestbookDAO;
import com.example.web03.model.guestbook.dto.GuestbookDTO;
 
@Controller
public class GuestbookController {
 
    /*
     * 의존관계:DataSource 로직이 바뀌면 전체가 영향을 받는다 그래서 controller는 스프링에서 만들어 관리 한다
     * 
     * GuestbookController => GuestbookDAOImpl=> SqlSession => SqlSessionFactory
     * =>DataSource
     */
 
    // GuestbookDAOImple 객체를 스프링에서 생성한 후 주입시킴
    @Inject
    GuestbookDAO guestbookdao;
 
    // 방명록 삭제
    @RequestMapping("guestbook/delete")
    public String delete(@ModelAttribute GuestbookDTO dto) {
 
        guestbookdao.gbDelete(dto.getIdx());
 
        // 리스트 갱신
        return "redirect:/guestbook/list";
    }
 
    @RequestMapping("/guestbook/update")
    public String update(@ModelAttribute GuestbookDTO dto) {
        // form에서 입력한 자료가 dto에 저장됨
        //원래 request.getparameter 해야 하는데 @ModelAttribute 가 알아서 해줌
        
        guestbookdao.gbUpdate(dto);
        
        
        //  /guestbook/list 로 포워딩
        return "redirect:/guestbook/list";
    }
 
    // 비번 체크
    @RequestMapping("/guestbook/view")
    public String view(int idx, String passwd, Model model) {
 
        // 비밀번호가 맞는지 체크
 
        int result = guestbookdao.pwdCheck(idx, passwd);
 
        if (result == 1) {
            // 맞으면 view.jsp 로 이동(수정/삭제화면)
            model.addAttribute("dto", guestbookdao.gbDetail(idx));
            
            //view.jsp 에서 수정 삭제 할 수 있다.
            return "/guestbook/view";
 
        } else {
 
            // 틀리면
            model.addAttribute("message""비밀번호가 일치하지 않습니다");
            return "redirect:/guestbook/list";
        }
 
    }
 
    // 방명록 쓰기
    // http://localhost:8282/web03/guestbook/write
    // 사용자가 입력한 내용이 @ModelAttribute GuestbookDTO dto에 저장된다.
    // dto가 null일때는 list 페이지
    // dto가 null 이 아닐때 insert 페이지
    @RequestMapping("/guestbook/write")
    public String write(@ModelAttribute GuestbookDTO dto, Model model) {
 
        // 입력한 내용이 없을때
        if (dto.getName() == null) {
 
            // web-inf/views/guestbook/list.jsp
            return "/guestbook/write";
        } else {
            // 입력한 내용이 있을때
            // 테이블에 insert
            // 목록 갱신
 
            guestbookdao.gbInsert(dto);
                //입력후 리스트로 이동
            return "redirect:/guestbook/list";
 
        }
 
    }
 
    // 방명록 리스트
    // http://localhost:8282/web03/guestbook/list
    @RequestMapping("/guestbook/list")
    public void list(Model model) {
 
        // 방명록 리스트를 받아옴
        List<GuestbookDTO> list = guestbookdao.gbList();
        // 모델에 저장
        model.addAttribute("items", list);
 
        // 리스트.size() 요소의 갯수
        model.addAttribute("count", list.size());
 
        // web-inf/views/guestbook/list.jsp
    }
 
}
 
cs


3. 방명록 DAO


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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package com.example.web03.model.guestbook.dao;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.inject.Inject;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
 
import com.example.web03.model.guestbook.dto.GuestbookDTO;
 
//저장소, DAO 데이터베이스 연동 관련 작업
@Repository
public class GuestbookDAOImpl implements GuestbookDAO {
 
    // mybatis 세션 객체를 스프링에서 생성하여 주입시킴
    // 스프링이 new sqlSession 해서 객체 생성시켜준다.
    @Inject
    SqlSession sqlSession;
 
    // 방명록 리스트
    @Override
    public List<GuestbookDTO> gbList() {
 
        List<GuestbookDTO> list = null;
 
        try {
            list = sqlSession.selectList("gbList");
 
            for (GuestbookDTO dto : list) {
                
                //리스트를 읽어 올때 아래 과정을 처리한 후 읽어 온다.
                // 줄바꿈 처리
                // 문자열.replace(A,B) 문자열 내부의 A를 B로 변경
                String content = dto.getContent();
                content = content.replace("\n""<br>");
 
                // 공백문자 처리
                // &nbsp : 스페이스 1개
                content.replace("  ""&nbsp;&nbsp;");
 
                // 태그방지처리
                // &lt는 less than ~ 보다 작다 <  모양만 같지 태그 문자가 아니다.
                content.replace("<""&lt");
                content.replace(">""&gt");
                dto.setContent(content);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
 
        }
 
        return list;
    }
 
    // 방명록 입력
    @Override
    public int gbInsert(GuestbookDTO dto) {
 
        int result = 0;
        try {
 
            // insert가 성공하면 affected row가 리턴됨
            // affected rows : insert query의 영향을 받은 레코드의 수
            result = sqlSession.insert("gbInsert", dto);
        } catch (Exception e) {
            e.printStackTrace();
 
        }
        return result;
    }
 
    // 수정삭제 비밀번호 확인
    @Override
    public int pwdCheck(int idx, String passwd) {
 
        int result = 0;
 
        try {
            // mybatis에 전달할 값이 2개인 경우
            // dto 또는 map으로 전달
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("idx", idx);
            map.put("passwd", passwd);
 
            result = sqlSession.selectOne("pwCheck", map);
        } catch (Exception e) {
            e.printStackTrace();
 
        }
        return result;
    }
 
    // 방명록 상세 불러오기
    @Override
    public GuestbookDTO gbDetail(int idx) {
 
        GuestbookDTO dto = null;
 
        try {
            dto = sqlSession.selectOne("gbDetail", idx);
        } catch (Exception e) {
            e.printStackTrace();
 
        }
        return dto;
    }
 
    @Override
    public int gbUpdate(GuestbookDTO dto) {
 
        int result = 0;
 
        try {
 
            // insert , update, delete 쿼리를 실행하면
            // affected rows 영향을 받은 행의 수 가 리턴됨
            result = sqlSession.update("gbUpdate", dto);
            System.out.println("jebal=" + result);
        } catch (Exception e) {
 
            e.printStackTrace();
        }
        return result;
    }
 
    // 방명록 삭제
    @Override
    public int gbDelete(int idx) {
 
        int result = 0;
        try {
            sqlSession.delete("gbDelete", idx);
        } catch (Exception e) {
 
            e.printStackTrace();
        }
 
        return result;
    }
 
}
 
cs


4. 방명록 mapper


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
<?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와 중복되지 않는 네임스페이스 기재 -->
<mapper namespace="guestbook">
 
 
 
    <select id="gbList" resultType="guestbookDto">
 
        select * from GUESTBOOK order by
        idx desc
 
    </select>
 
 
    <insert id="gbInsert">
 
        insert into guestbook
        (idx,name,email,passwd,content)
        values(
 
        (select nvl(max(idx)+1,1from guestbook),
        #{name}, #{email},
        #{passwd}, #{content}
        )
 
    </insert>
 
 
 
    <select id="pwCheck" resultType="int">
 
        select count(*from guestbook
        where idx=#{idx} and passwd=#{passwd}
 
    </select>
 
 
 
 
    <select id="gbDetail" resultType="guestbookDto">
 
        select * from GUESTBOOK
        where
        idx=#{idx}
 
    </select>
 
 
 
<!-- 업데이트 할대는 반드시 where절에 삭제 행의 번호가 있어야 한다. -->
    <update id="gbUpdate">
 
 
        update guestbook
        set name=#{name}, email=#{email},
        content=#{content}
        where idx=#{idx}
 
 
    </update>
 
 
 
    <delete id="gbDelete">
 
        delete from guestbook where idx=#{idx}
 
    </delete>
 
 
 
 
</mapper>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cs



5.방명록 리스트 페이지 


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
    <!-- <div style="text-align: center;"> -->
    <%@ include file="../include/menu.jsp"%>
    <h2 style="text-align: center;">방명록</h2>
 
    <div style="text-align:center; width: 600px;">
        게시물수:${count}, <a href="${path}/guestbook/write">글쓰기</a>
    
    <br>
    
    
    <!-- 컨트롤러에서 redirect 로 넘어오면 앞에 param을 붙여준다. -->
    
    <span style="color:red;">${param.message}</span>
    </div>
 
    <c:forEach var="row" items="${items}">
 
        <!-- 폼이 테이블을 감싼 구조 -->
        <form action="${path}/guestbook/view">
            <!-- 방명록리스트 -->
            <table align="center" border="1" style="width: 600px;">
 
 
                <tr>
                    <td>이름</td>
                    <td>${row.name}</td>
                    <td>날짜</td>
                    <td>${row.post_date}</td>
                </tr>
 
                <tr>
                    <td>이메일</td>
                    <td colspan="3">${row.email}</td>
                </tr>
 
                <tr>
 
                    <td colspan="4">${row.content}</td>
                </tr>
                <tr>
 
            <!-- 게시물 번호는 hidden field로 넘김 -->
                    <td colspan="4">비밀번호 
                    <input type="hidden" name="idx" value="${row.idx}">
                     <input type="password" name="passwd">
                    <input type="submit" value="수정/삭제">
 
                    </td>
                </tr>
 
            </table>
        </form>
    </c:forEach>
 
 
</body>
</html>
cs


6.방명록작성  페이지 


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
<%@ 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>
 
 
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script
 
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
 
 
<script>
    
    $(document).ready(function(){
        
        $("#content").summernote({
            
            height:300,
            width:800
            
        });
    });
 
 
 
</script>
 
 
</head>
<body>
    <%@ include file="../include/menu.jsp"%>
    
    <h2 style="text-align:center;">방명록 작성</h2>
    
    <form name="form1" method="post" action="${path}/guestbook/write">
    <table border="1" style="width:800px;" align="center">
        
        <tr>
            <td>이름</td>
            <td><input name="name" size="20"
            value="${sessionScope.name}"></td>
            
        </tr>
    
        <tr>
            <td>이메일</td>
            <td><input name="email" size="40"></td>
        </tr>
        
 
        <tr>
            <td>비밀번호</td>
            <td><input type="password" name="passwd" size="20"></td>
            
        </tr>
 
 
        <tr>
            <td colspan="2">
            <textarea name="content" id="content" rows="20" cols="80"></textarea></td>
        </tr>
 
        <tr>
            <td colspan="2">
            <input type="submit" value="확인">
            <input type="reset" value="취소"></td>
        </tr>    
        </table>
    </form>
</body>
</html>
cs



7.방명록 상세 보기 수정삭제  페이지


 

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
94
95
96
97
98
99
100
101
102
103
104
105
106
<%@ 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>
 
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script
 
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
 
 
<script>
    
    $(document).ready(function(){
        
        $("#content").summernote({
            
            height:300,
            width:800
            
        });
    });
 
 
 
</script>
 
 
<script>
    $(document).ready(function() {
 
        $("#btnUpdate").click(function() {
 
            alert("오잉");
            //버튼 클릭이벤트
            //GuestbookController로 수정할 자료 전송
            document.form1.action = "${path}/guestbook/update";
            document.form1.submit();
 
        });
        
        //삭제하기 
        $("#btnDelete").click(function(){
            
            /* confirm 에서 확인 눌렀을때 true를 리턴한다. */
            
            if(confirm("삭제하시겠습니까?")){
            
                //document.폼 이름 . action = 주소 
                
                document.form1.action ="${path}/guestbook/delete";
                document.form1.submit();
            }
            
        });
    });
</script>
 
 
</head>
<body>
    <%@ include file="../include/menu.jsp"%>
    
    
    <!-- //폼의 이름을 써줘야 한다. -->
    <form name="form1">
        <!-- 방명록리스트 -->
        <table align="center" border="1" style="width: 600px;">
 
 
            <tr>
                <td>이름</td>
                
                <!-- td에 수정할수 있게 input type 태그를 지정해 줬다. -->
                
                <td><input name="name" value="${dto.name}"></td>
                <td>날짜</td>
                <td>${dto.post_date}</td>
            </tr>
            <tr>
                <td>이메일</td>
                <td colspan="3"><input name="email" value="${dto.email}"></td>
            </tr>
            <tr>
                <td colspan="4"><textarea name="content" id="content" rows="5" cols="60">
                ${dto.content}</textarea></td>
            </tr>
            <tr>
                <!-- 게시물 번호는 hidden field로 넘김 -->
                <td colspan="4">
                <input type="hidden" name="idx" value="${dto.idx}"
                <input type="button" id="btnUpdate" value="수정"
                <input type="button" id="btnDelete" value="삭제">
                </td>
            </tr>
 
        </table>
    </form>
</body>
</html>
cs


반응형

댓글