728x90

0415_mvcboard.zip
4.40MB

-개발환경-

IDE : Eclipse IDE for Enterprise Java Developers ver-2020-06 (4.16.0)
Tomcat : Tomcat v8.0 Server
JAVA : JAVA8
oracle : oracle 11g

-GUI

-게시글목록-
-게시글화면-
-게시글수정화면-

 

-구성도

 

-DB(Oracle)

 

-요약-

 

-마침글-

.

'21년이전 > 국비-JSP+oracle' 카테고리의 다른 글

JSP+Oracle-Freeboard  (0) 2021.04.13
JSP+Oracle - Category  (0) 2021.04.07
JSP+Oracle-guestbook  (0) 2021.04.01
728x90

0408_freeboard.zip
4.41MB

-개발환경-

IDE : Eclipse IDE for Enterprise Java Developers ver-2020-06 (4.16.0)
Tomcat : Tomcat v8.0 Server
JAVA : JAVA8
oracle : oracle 11g

-GUI

-구성도

 

-DB(Oracle)

 

-요약-


HTML 


-label를 다른 외부태그와 묶어주기-
<label for="content">내용</label>       <!-- for="name"부분에 아이디가 들어감 -->

CSS


style="resize: none;" 크기 고정


JAVASCRIPT

자바스크립트의 함수의 인수로 문자열을 넘길때는 반드시 따옴표로 묶어줘야한다.
자바스크립트의 함수로 인수를 넘길 때, 이스케이프시퀀스가 포함된 문자열을 넘기면
함수가 동작되지 않는다.
//java나 jsp의 replace 메소드는 모든 내용을 일괄적으로 치환하지만 , 
//자바스크립트의 replace함수는 맨 처음의 1개만 치환시킨다.
//즉, 인수로 넘어온 데이터에 더이상 <br/>이 나타나지 않을 때까지 반복하며  '\r\n'으로 치환시켜야 한다.

-특정문자열 반복하여 찾기-
while(content.indexOf('<br/>') != -1){
content = content.replace('<br/>','\r\n');
}

JAVA


JSP

-jsp에서 사용하는 시스템 영역과 유효 범위(scope)-
//pageContext => 현재 보고 있는 페이지
//request => 현재 보고있는 페이지의 다음 페이지
//session => 브라우저가 실행되면 생성되고 브라우저가 종료되면 소멸되는 영역
//application  => 서버가 실행되면 생성되고 서버가 종료되면 소멸되는 영역

request.getRemoteAddr()  //  접속자 아이피받아옴


JQUERY


JSTL+EL


-함수사용-
${fn:replace(vo.subject,'<','&lt;')}
-날짜패턴지정-
<fmt:formatDate value="${vo.writeDate}" pattern="yyyy-MM-dd(E)" />

EL

${pageContext.request.remoteAddr} // 접속자 아이피 받음


IBATIS


MYBATIS

nextval => 시퀀스를 증가시킨다.
currval => 현재 시퀀스 값을 의미한다.
ex)
insert into category (idx, category, ref, lev, seq) 
values (category_idx_seq.nextval, #{category}, category_idx_seq.currval, 0, 0)



SQL


ORACLE
-테이블 행수 검사-
select count(*) from freeboard
-삼중 for문 및  CDATA 이용 -
<!-- <![CDATA[와 ]]> 사이에 입력된 내용은 무조건 문자열로 취급된다. 
       GG는 별명이다.
-->
<!-- rownum은 *을 못씀.
rownum , rnum에는 index번호가 들어있음
 -->
<![CDATA[
select * from (
select rownum rnum, GG.* from(
select * from freeboard order by idx desc
) GG where rownum <= #{endNo}
) where rnum >= #{startNo}
]]>




 

-마침글-

.

'21년이전 > 국비-JSP+oracle' 카테고리의 다른 글

JSP+Oracle-MVC패턴게시판  (0) 2021.04.16
JSP+Oracle - Category  (0) 2021.04.07
JSP+Oracle-guestbook  (0) 2021.04.01
728x90

-개발환경-

IDE : Eclipse IDE for Enterprise Java Developers ver-2020-06 (4.16.0)
Tomcat : Tomcat v8.0 Server
JAVA : JAVA8
oracle : oracle 11g

-GUI

-구성도

 

-DB(Oracle)

 

-요약-

JAVASCRIPT


-onsubmit 이벤트-
       onsubmit 이벤트는 form의 submit 버튼이 클릭되면 실행되는 이벤트이다. 
       onsubmit 이벤트에서 함수를 실행해서 form에 입력된 데이터가 정상적인 데이터인가 유효성을 검사해서 
       검사 결과가 정상이면 true 
       오류가 발생되면 false를 리턴하게 만든다. 
       onsubmit="return javascript함수(this)"  형태로 코딩하며 javascript 함수의 실행 결과인 
       return 값이  true면 action 속성에서  지정한 페이지로 넘겨주고 return 값이 false면 현재 페이지에  
       그대로 머물러 있게한다. 

-멀티서브밋-
html에서 ..
<input type="button" value="수정" onclick="mySubmitUpdate(${formName})" />
script문에서..
function mySubmitUpdate(obj){
//console.log(obj.category.value);
if(!obj.category.value.trim()){
alert(' 수정할 카테고리를 입력하세요.');
obj.category.value ='';
obj.category.focus();
}else {
obj.action = 'update.jsp'; //인수로 넘어온 폼의 action페이지를 변경한다.
obj.submit();  //action 페이지를 호출하고 폼의 데이터를 전송한다.
}
}
이렇게하면,  데이터가 신기하게 잘넘어감..

HTML


JQUERY


-함수 인수 이용 예시-
$('#form').submit(function(event){
//preventDefault() : event로 넘어온 기본 이벤트의 
//실행을 중지시킨다.
event.preventDefault();
}

-함수 인수 이용 예시2-
item : sub_form 이라는 class가 지정된 index 번째 객체가 저장된다.
$('.sub_form').each(function(index,item){
//addClass() : each() 메소드를 통해서 반복되는 객체에 class 속성을 추가한다.
$(item).addClass('sub_form'+index);
}

-submit 이벤트-
아이디가 form인 태그에서 submit 버튼이 클릭되었을때 발생하는 이벤트.
$('#form').submit(function(event){
~
});

JSP


-useBean,setProperty-
<jsp:useBean id="vo" class="com.koreait.vo.CategoryVO">
<jsp:setProperty property="*" name="vo"/>
</jsp:useBean>
//class 에 해당하는 객체를 생성해서 변수이름을 vo로 지정.
//request.getParameter 자동효과로 얻어온 데이터를 vo 객체에 setter효과로 저장됨.

SQL 


ORACLE


JSTL


jstl : JSP 개발을 단순화하기위한 태그 라이브러리 
<!--  jstl을 이용해 대입문,제어문,서식,함수를 사용하기 위해 아래의 내용을 코딩한다. -->

<%@ 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"%><!-- 함수 -->

jstl은 html태그 내부에 쓰이면 에러 발생.

jstl 조건문
else를 사용할 수 없다.
ex)
 <c:if test="${조건식}">
  조건식이 참일 경우 실행할 문장
 </c:if>
 
jstl 대입문
 <c:set var="변수 이름" value="변수에 저장할 데이터"/>

 jstl 반복문
초기치 부터 증가치 만큼 증가하며 최종치까지 반복한다.
 증가치가 생략가능으로, 1이 기본값으로  적용.
 증가치는 반드시 양수만 사용할 수 있다.
<c:forEach var="변수이름" begin="초기치" end="최종치" [step="증가치"]>
반복할 문장
</c:forEach>

jstl 반복문2
객체에 저장된 내용이 처음부터 마지막 까지 차례대로 대입되며 반복한다.
<c:forEach var="변수 이름" items=${배열 또는 List 객체}>
반복할 문장
</c:forEach>

jstl 함수
${fn:함수이름(인수)}

jstl 날짜 서식 적용,출력
날짜 서식을 지정하고 출력하는 방법이다. 
pattern유형은 자바와 동일하다.
<fmt:formatDate value="${날짜 데이터}" pattern="날짜 서식"/>


EL


EL(Expression Language) : 내장 객체의 데이터를 자바를 이용하지 않고
 쉽고 간결하게 꺼낼수 있게 하는 기술이다.
EL을 사용하면 request영역에 저장된 데이터를 받는 
처리 없이 request영역에 이미 저장된 객체를  사용 할수 있다.
ex)
GuestbookList guestbookList=(GuestbookList)request.getAttribute("guestbookList");  
out.println(guestbookList); 해당 2문장과 같은 기능을 아래명령어 EL로 표현
 ${guestbookList}
 
 EL표기로  ${객체이름.멤버변수이름} 을 사용할시 , 자동으로 getter효과가 발생됨. 

iBATIS


sql명령 :
iBATIS는 sql 명령내에 변수를 #과 #사이에 적는다.
myBATIS는 #{변수} 형식으로 적는다

.xml파일에서
parameterClass : db로 보내는 데이터의 타입을 적는다. 
resultClass : db로부터 받는 데이터의 타입을 적는다.


myBATIS


sql명령 : 
myBATIS는 sql 명령내에 변수를 #{변수} 형식으로 적는다

.xml파일에서
parameterType : db로 보내는 데이터의 타입을 적는다. 
resultType : db로부터 받는 데이터의 타입을 적는다.

Service.java파일에서
테이블을 변경하는 insert,delete,update sql은 작업 결과를 테이블에 
반영시키기 위해서  작업이 완료되면 commit() 메소드를 실행해야 함
mapper.commit();
mapper.close();

 

-마침글-

.

'21년이전 > 국비-JSP+oracle' 카테고리의 다른 글

JSP+Oracle-MVC패턴게시판  (0) 2021.04.16
JSP+Oracle-Freeboard  (0) 2021.04.13
JSP+Oracle-guestbook  (0) 2021.04.01
728x90

-개발환경-

IDE : Eclipse IDE for Enterprise Java Developers ver-2020-06 (4.16.0)
Tomcat : Tomcat v8.0 Server
JAVA : JAVA8
oracle : oracle 11g

 

-구성도-

 

 

-listView.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!--  jstl을 이용해 대입문,제어문,서식,함수를 사용하기 위해 아래의 내용을 코딩한다. -->
<%@ 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"%><!-- 함수 -->
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<fmt:requestEncoding value="UTF-8"/>
 
    <c:set var="view" value="${guestbookList.list}"/>
    <table width="1000" align="center" border="1" cellpadding="5" cellspacing="0">
        <tr>
            <th>방명록 보기</th>
        </tr>
        <tr>
            <td align="right">
                ${guestbookList.totalCount}개 (${guestbookList.currentPage}/ ${guestbookList.totalPage})Page
            </td>
        </tr>
        <tr>
            <td>
            
                 <c:if test="${view.size() == 0}">
                    <marquee>테이블에 글이 존재하지 않습니다.</marquee>
                </c:if>
                
                <c:if test="${view.size() != 0}">
                
                    <jsp:useBean id="date" class="java.util.Date"/>
                
                    <c:forEach var="vo" items="${view}">
                        
                        <table width="99%" align="center" border="1" cellpadding="5" cellspacing="0"> <!-- 바깥표의 넓이에 99퍼 맞춘다 -->
                            <tr>
                                <td>
                                      ${vo.idx}.
                                     
                                     <c:set var="name" value="${fn:replace(vo.name,'<','&lt;')}"/>
                                     <c:set var="name" value="${fn:replace(name,'>','&gt;')}"/>
                                     ${name}님(${vo.ip}})이
                                     
                                     <c:if test="${date.year == vo.writedate.year && date.month == vo.writedate.month && date.date == vo.writedate.date }">
                                         <fmt:formatDate value="${vo.writedate}" pattern="HH:mm"/>
                                     </c:if>
                                     <c:if test="${date.year != vo.writedate.year || date.month != vo.writedate.month || date.date != vo.writedate.date }">
                                         <fmt:formatDate value="${vo.writedate}" pattern="yyyy/MM/dd(E)"/>
                                     </c:if>
                                     에 남긴글
                                     
                                     <c:set var="memo" value="${fn:replace(vo.memo,'<','&lt;')}"/>
                                     <c:set var="memo" value="${fn:replace(memo,'>','&gt;')}"/>
                                     <c:set var="memo" value="${fn:replace(memo,enter,'</br>')}"/>
                                    ${memo} 
                                    
                                     <input type="button" value="수정" onclick="location.href='selectByIdx.jsp?idx=${vo.idx}&currentPage=${guestbookList.currentPage}&job=update'"/>
                                     <input type="button" value="삭제" onclick="location.href='selectByIdx.jsp?idx=${vo.idx}&currentPage=${guestbookList.currentPage}&job=delete'"/>
                                     
                                </td>
                            </tr>
                        </table>
                        
                    </c:forEach>
                </c:if>
                
            </td> 
        </tr>
        
        <!-- 페이지 이동 버튼 -->
        <tr>
            <td align="center">
            
                <!--  맨 앞으로 -->
                <c:if test="${guestbookList.currentPage> 1}">
                    <input class="button button1" type="button" value="맨앞" title="첫 번째 페이지로 이동" onclick="location.href='?currentPage=1'"/>
                </c:if>
                <c:if test="${guestbookList.currentPage <= 1}">
                    <input class="button button2" type="button" value="맨앞" disabled="disabled" title="이미 첫 번째 페이지입니다."/> 
                </c:if>    
            
                <!--  10페이지 앞으로 -->    
                <c:if test='${guestbookList.startPage>1}'>
                    <input class="button  button1" type="button" value="이전" title="이전 10페이지로 이동" onclick="location.href='?currentPage=${guestbookList.startPage -1}'"/>    
                </c:if>
                <c:if test='${guestbookList.startPage<=1}'>
                    <input class="button button2" type="button" value="이전" disabled="disabled" title="이미 첫 번째 10페이지입니다."/> 
                </c:if>
                <!--  페이지 이동 -->                
                <c:forEach var="i" begin="${guestbookList.startPage}" end="${guestbookList.endPage}">
                    <c:if test="${guestbookList.currentPage==i}">
                        <input class="button button2" type="button" value="${i}" disabled="disabled"/>
                    </c:if>
                    <c:if test="${guestbookList.currentPage!=i}">
                        <input class="button button1" type="button" value="${i}" onclick="location.href='?currentPage=${i}'"/>
                    </c:if>
                </c:forEach>
    
                <!--  10페이지 뒤로 -->
                <c:if test="${guestbookList.endPage < guestbookList.totalPage}">
                    <input class="button  button1" type="button" value="다음" title="다음 10페이지로 이동" onclick="location.href='?currentPage=${guestbookList.endPage +1}'"/>    
                </c:if>
            
                <c:if test="${guestbookList.endPage >= guestbookList.totalPage}">
                    <input class="button button2" type="button" value="다음" disabled="disabled" title="이미 마지막 10페이지입니다."/> 
                </c:if>
            
                <!--  맨 뒤로 -->
                <c:if test="${guestbookList.currentPage < guestbookList.totalPage}">
                    <input class="button  button1" type="button" value="맨뒤" title="마지막 페이지로 이동" onclick="location.href='?currentPage=${guestbookList.totalPage}'"/>    
                </c:if>
            
                <c:if test="${guestbookList.currentPage >= guestbookList.totalPage}">
                    <input class="button button2" type="button" value="맨뒤" disabled="disabled" title="이미 마지막 페이지입니다."/> 
                </c:if>
            
            </td>
        </tr>
        
        <!-- 글쓰기 버튼 -->
        <tr>
            <td align="right">
                <input type="button" value="글쓰기" onclick="location.href='insert.jsp'"/>
            </td>
        </tr>
    </table>
 
 
</body>
</html>
cs
더보기

-Description-

외부의 request에 저장된요소 guestbookList , enter('\r\n' 이라는 문자열)

17 :  request.setCharacterEncoding("UTF-8");기능을 jstl로 수행 

19 : 이전 페이지의 request에 저장된 guestbookList의 
guestbookList.getList() 결과가 view에 저장됨,   EL,JSTL 표현을 사용

26 : 토탈 게시글수, 페이지정보출력

32~34 : 테이블에 저장된 글이 없으면 브라우저에 글이 없다고 출력한다. 

36~72 : 테이블에 저장된 글이 있으면 브라우저에 목록을 출력한다.

38 : useBean액션 태그를 이용해 오늘 날짜를 기억하는 Date클래스 객체를 선언한다.
Date date = new Date();와 같은 기능이 실행된다.
useBean액션 태그의 id는 객체변수이름 ,  class는 클래스명포함한 경로

40 : 반복문 수행, 변수명 vo 에 GuestbookVO 객체가 하나씩 담김.

47~48 :  .replace("<","&lt;").replace(">","&gt;")  와 동일한 수행 ,
47줄을 보면 알다 시피,  replace함수의 첫 인자로 이용할 변수이름이 쓰여졌다.

51~56 : 오늘 입력한 글은 시간만 나오게 하고 
어제 이전에 입력한 글은 날짜만 나오게 한다. 

59~61 : '<' , '>'  '\r\n' 을 특수기호로 인식하지 않게 한다.

64,65 :  글 수정,삭제 버튼 추가,  
두 버튼 모두  selectByIdx.jsp 로 이동. 
전달 되는것 = idx , currentPage , job

78~125 : 페이지 이동 버튼 다루는 구간.

83 : currentPage=1 로 전달 한다는데, 이게 어떻게 가능하냐하면, ..
현재 화면을 호출한 list.jsp가  pageContext.forward("listView.jsp"); 을 사용하였으므로,
currentPage를 처리하는 곳은 list.jsp이다.

128~132 : 글쓰기 버튼 구간으로, 클릭시 insert.jsp 로 이동

 

-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
<%@page import="com.koreait.vo.GuestbookList"%>
<%@page import="com.koreait.service.SelectService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
     request.setCharacterEncoding("UTF-8");
int currentPage=1;
     try{
         currentPage=Integer.valueOf(request.getParameter("currentPage"));
    }catch(NumberFormatException e){}
     
     GuestbookList guestbookList = SelectService.getInstance().selectList(currentPage);
     request.setAttribute("guestbookList",guestbookList);
     
     request.setAttribute("enter", "\r\n");
     
     pageContext.forward("listView2.jsp");
 %>
</body>
</html>
cs
더보기

-Description-

역할 : currentPage를 넘겨받아 currentPage에 해당되는 1페이지 분량의 글 목록을 
테이블에서 얻어와서 request 영역에 저장한 후 1페이지 분량의
글을 listView.jsp로 넘겨준다.

외부의 request에 저장된요소 currentPage or null

14~17 : request로 부터 받은 currentPage를 저장.

19~20 :  1페이지 분량의 글목록과 페이징작업에 사용할 8개의 변수가 초기화된 
객체(GuestbookList 타입)를 request영역에 저장한다

22 : 글을 입력할 때 엔터키를 눌러 줄을 바꿔서 입력한 경우 저장된 값은 \r\n이므로 브라우저에는 <br/> 태그로 바꿔 출력하기 위해 작업을 진행한다. 
 바꿔치기 작업은 listView.jsp에서 수행됨 

24 : forward를 사용하여 .jsp파일을 호출 하였으므로.. 호출된 .jsp파일역시 request 영역이 된다.
ps)
request 영역은 요청을 받아서 응답하기까지 객체가 유효한 영역입니다.
Servlet에서 forward 또는 include를 사용하면, request 요청 객체가 공유되어서 request 영역이 됩니다.
Servlet에서 JSP로 객체를 보낼 때 사용하는 방법입니다.

 

-selectByIdx.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
<%@page import="com.koreait.vo.GuestbookVO"%>
<%@page import="com.koreait.service.SelectService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
 <%
     request.setCharacterEncoding("UTF-8");
     int idx = Integer.valueOf(request.getParameter("idx"));
     int currentPage = Integer.valueOf(request.getParameter("currentPage"));
     String job= request.getParameter("job");
     
     GuestbookVO vo = SelectService.getInstance().selectByIdx(idx);
     
     if ( vo == null){
         out.println("<script>alert('"+idx+"번 글은 존재하지 않습니다."+"')</script>");
     }else{
         request.setAttribute("vo", vo);
         request.setAttribute("currentPage", currentPage);
         request.setAttribute("enter", "\r\n");
         pageContext.forward(job+".jsp");
     }
 %>
 
</body>
</html>
cs
더보기

-Description

수정 또는 삭제할 글 1건을 얻어와서 request 영역에
 저장한 후 수정 또는 삭제할 글을 브라우저에 표시하는 페이지로 넘겨준다. 

15~17: 외부로부터 데이터를 가져온다.  idx,currentPage,job

19 : 수정 또는 삭제할 글 1건을 얻어온다.

27 :  수정 또는 삭제할 글이 존재할 시에  delete.jsp 혹은 update.jsp가 수행됨

-SelectService.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
package com.koreait.service;
 
import java.sql.SQLException;
import java.util.HashMap;
 
import com.ibatis.sqlmap.client.SqlMapClient;
import com.koreait.dao.GuestbookDAO;
import com.koreait.ibatis.MyAppSqlConfig;
import com.koreait.vo.GuestbookList;
import com.koreait.vo.GuestbookVO;
 
public class SelectService {
 
    private static SelectService instance = new SelectService();
    private SelectService() { }
    public static SelectService getInstance() { return instance; }
    
    public GuestbookList selectList(int currentPage) {
        
        System.out.println("SelectService 클래스의 selectList() 메소드");
        SqlMapClient mapper = MyAppSqlConfig.getSqlMapInstance();
        
        GuestbookList guestbookList = null;
 
        GuestbookDAO dao = GuestbookDAO.getinstance();
        
        try {
            int pageSize = 10;
 
            int totalCount = dao.selectCount(mapper);
            
            guestbookList = new GuestbookList(pageSize, totalCount, currentPage);
            
            HashMap<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("startNo", guestbookList.getStartNo());
            hmap.put("endNo", guestbookList.getEndNo());
//            mysql은 아래와 같이 'endNo' 대신 'pageSize'를 저장해서 넘겨주면 된다. 
//            hmap.put("pageSize", guestbookList.getPageSize());
            
            guestbookList.setList(dao.selectList(mapper, hmap));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return guestbookList;
    }
    
    public GuestbookVO selectByIdx(int idx) {
        System.out.println("SelectService의 selectByIdx()메소드");
        SqlMapClient mapper = MyAppSqlConfig.getSqlMapInstance();
        
        GuestbookVO vo = null;
        try {
        vo = GuestbookDAO.getinstance().selectByIdx(mapper,idx);
        }catch(SQLException e) {
            e.printStackTrace();
        }
        return vo;
    }
    
}
 
 
 
 
 
 
 
 
 
cs
더보기

-Description

Singleton 패턴

18 : list.jsp에서 호출이 됨. 화면에 표시할 페이지 번호를 넘겨받고 mapper를 얻어온 후
 DAO 클래스의 1페이지 분량의 글 목록을 얻어오는 메소드를 호출하는 메소드

21 : SqlMapClient  객체 생성

23 : 페이지 분량의 글과 페이징 작업에 사용할 8개의 변수를 저장해서 리턴시킬 객체를 선언한다.

28 :  1페이지당 표시할 글의 개수를 정한다.

30 : 테이블에 저장된 전체 글의 개수를 얻어온다. ( 실제 sql 수행 )

32 : pageSize, totalCount, currentPage를 GuestbookList 클래스의 생성자로 넘겨서
 1페이지 분량의 글을 저장하고 페이징 작업에 사용할 변수를 초기화 시키는 
GuestbookList 클래스 객체를 생성한다.

34~36 : <String,Integer> 형식의 해쉬맵생성후,  한 페이지의 첫글번호와 끝번호를 전달.

40 : dao를 통해 한페이지 분량의 게시글을 얻어와서 guestbookList의 list를 초기화 시킨다.( 실제 sql 수행 )

45 : guestbookList 을 리턴시킴

48 : selectByIdx.jsp에서 호출이됨
수정 또는 삭제할 글번호를 넘겨받고 
mapper를 얻어온후 DAO클래스의 글 1건을 얻어옴

50 : SqlMapClient 객체를 생성.

54 : DAO를 통해 특정 인덱스에 속하는 게시글 하나를 꺼내온다.(실제 sql 수행)

58 : 게시글 하나 반환.

-InsertService.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
package com.koreait.service;
 
import java.sql.SQLException;
 
import com.ibatis.sqlmap.client.SqlMapClient;
import com.koreait.dao.GuestbookDAO;
import com.koreait.ibatis.MyAppSqlConfig;
import com.koreait.vo.GuestbookVO;
 
public class InsertService {
 
    private static InsertService instance=new InsertService();
 
    private InsertService(){
        
    }     
    public static InsertService getInstance() {
        return instance;
    }
    
    
    public void insert(GuestbookVO vo) {
        System.out.println("InsertService클래스의 insert()메소드");
        
        SqlMapClient mapper=MyAppSqlConfig.getSqlMapInstance();
        
        try {
            GuestbookDAO.getinstance().insert(mapper,vo);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 
cs
더보기

-Description

Single톤 패턴임.

22 : 테이블에 저장할 객체 vo를 들여오고 ,   mapper와 dao를 통하여 db 작업을 수행.

25 : SqlMapClient  객체 생성.
mapper에는 데이터베이스에 연결하는 connection과 연결된 후 실행할
sql 명령(guestbook.xml)이 저장되어 있다.

28 : DAO 클래스를 통해  insert sql 명령이 실행되게 만든다. (실제 sql 수행)

-MyAppSqlConfig.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.koreait.ibatis;
 
import java.io.Reader;
 
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
 
public class MyAppSqlConfig {
    private static final SqlMapClient sqlMap;//이게 mapper임
    static {    
        try {
            String resource = "com/koreait/ibatis/SqlMapConfig.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException ("Error : " + e);
        }
    }
    
    public static SqlMapClient getSqlMapInstance() {
        return sqlMap;
    }
}
 
cs
더보기

-Description

ibatis 설정 파일

10 : SqlMapClient 타입의 상수를 정적으로 생성.
final로 선언된 변수는 상수로 사용되므로 선언과 동시에 반드시 초기화되어야 한다.

11 : static 변수 초기화 블럭

13~15 : SqlMapConfig.xml( iBatis 설정정보 파일) 파일을 통하여 SqlMapClient  객체 생성

22~24 : 생성된 static상수인 SqlMapClient  객체를 반환.

-SqlMapConfig.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
<?xml version="1.0" encoding="UTF-8"?>
<!-- DOCTYPE이 sqlMapConfig은 iBATIS의 환경을 설정하는 xml 파일이다. -->
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <!-- 데이터베이스 연결 정보가 저장된 properties 파일의 프로젝트상의 경로 -->
    <properties resource="com/koreait/ibatis/db.properties" />
    <settings 
        cacheModelsEnabled="true" 
        enhancementEnabled="true"
        lazyLoadingEnabled="true" 
        maxRequests="32" 
        maxSessions="10"
        maxTransactions="5" 
        useStatementNamespaces="false" 
    />
    
    <!--  별명을 설정한다. -->
    <typeAlias alias="vo" type="com.koreait.vo.GuestbookVO" />
    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
            <property name="JDBC.Driver" value="${driver}" />
            <property name="JDBC.ConnectionURL" value="${url}" />
            <property name="JDBC.Username" value="${username}" />
            <property name="JDBC.Password" value="${password}" />
        </dataSource>
    </transactionManager>
    <!-- 데이터베이스에 연결한 후 실행할 sql 명령이 저장된 파일의 프로젝트상의 경로 -->
    <sqlMap resource="com/koreait/ibatis/guestbook.xml" />
</sqlMapConfig>
 
 
 
 
 
 
 
 
 
 
cs
 
더보기

-Description

iBATIS 설정 파일

2 : DOCTYPE이 sqlMapConfig은 iBATIS의 환경을 설정하는 xml 파일이라는 의미.

-db.properties-

1
2
3
4
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=Shin
password=0000
cs
더보기

-Description

DB드라이버정보, url ,  DB계정정보가 담긴 파일.

-guestbook.xml-

29~35 : 3중 select

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
<?xml version="1.0" encoding="UTF-8" ?>
<!-- DOCTYPE이 sqlMap인 xml 파일은 처리할 SQL 명령을 기억하는 xml 파일이다. -->
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<!-- 윗 줄은 CDN -->
<sqlMap namespace="com.koreait.vo.GuestbookVO"> 
    <!--  ibatis의 경우, namespace에는 무엇을 적어도 상관없음 -->
    <!-- id : SQL 명령을 식별한다. -->
    <!-- parameterClass : SQL 명령으로 전달되는 데이터의 타입을 적는다. -->
    <!-- resultClass : SQL 명령문에의해 출력되는 데이터의 타입을 적는다. -->
    
    <!-- 게시판에 글 1건을 저장한다. -->
    <insert id="insert" parameterClass="vo">
        <!-- nextval => 시퀀스 값을 1증가 시킨다. -->
        insert into guestbook (idx,name,password,memo,ip) values (guestbook_idx_seq.nextval,#name#,#password#,#memo#,#ip#)
    </insert>
    
    <!--  테이블에 저장딘 전체 글의 갯수를 얻어온다.  -->
    <select id= "selectCount" resultClass = "int">
        select count(*) from guestbook
    </select>        
    
    <!--  1페이지 분량의 글 목록을 얻어온다. -->
    <select id= "selectList" parameterClass="java.util.HashMap" resultClass="vo">
        <!-- <![CDATA[와 ]]> 사이에 입력된 내용은 무조건 문자열로 취급된다. -->
        <!-- rownum은 *을 못씀.
            rownum , rnum에는 index번호가 들어있음
            
         -->
        <![CDATA[
        select * from (
            select rownum rnum, GG.* from(
                select * from guestbook order by idx desc
            ) GG where rownum <= #endNo#
        ) where rnum >= #startNo#
        ]]>
        
        
    </select>
    
    <!-- 글 1건을 얻어온다-->
    <select id="selectByIdx" parameterClass="int" resultClass="vo">
        select * from guestbook where idx=#idx#
    </select>
    
    <delete id="delete" parameterClass="int">
        delete from guestbook where idx = #idx#
    </delete>
    
    <update id="update" parameterClass="com.koreait.vo.GuestbookVO">
        update guestbook set name = #name#, memo = #memo# where idx = #idx#
    </update>
</sqlMap>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cs
더보기

-Description

29~35 : 3중 select

-GuestbookDAO.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
75
76
77
78
79
80
package com.koreait.dao;
 
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
 
import com.ibatis.sqlmap.client.SqlMapClient;
import com.koreait.vo.GuestbookVO;
 
public class GuestbookDAO {
    private static GuestbookDAO instance=new GuestbookDAO();
    
    private GuestbookDAO() {
    }
    
    public static GuestbookDAO getinstance() {
        return instance;
    }
    
    public void insert(SqlMapClient mapper,GuestbookVO vo) throws SQLException {
        System.out.println("GuestbookDAO 클래스의 insert()메소드");
        mapper.insert("insert", vo);
    }
    
    public int selectCount(SqlMapClient mapper) throws SQLException{
        System.out.println("GuestbookDAO 클래스의 selectCount() 메소드");
        return (int)mapper.queryForObject("selectCount");
    }
    
    public ArrayList<GuestbookVO> selectList(SqlMapClient mapper,HashMap<String,Integer> hmap) throws SQLException{
        System.out.println("GuestbookDAO클래스의 SelectList()메소드");
        return (ArrayList<GuestbookVO>) mapper.queryForList("selectList",hmap);//아이디는 메소드이름과 동일하게하는게 전통
    }
 
    public GuestbookVO selectByIdx(SqlMapClient mapper, int idx) throws SQLException {
        System.out.println("GuestbookDAO의 selectByIdx()메소드");
        return (GuestbookVO) mapper.queryForObject("selectByIdx", idx);
    }
 
    public void delete(SqlMapClient mapper, int idx) throws SQLException {
        System.out.println("GuestbookDAO클래스의 delete()메소드");
        mapper.delete("delete",idx);
    }
 
    public void update(SqlMapClient mapper, GuestbookVO vo) throws SQLException {
        System.out.println("GuestbookDAO클래스의 update()메소드");
        mapper.update("update",vo);
    }
 
    public int selectCountMemo(SqlMapClient mapper, String item) throws SQLException {
        System.out.println("GuestbookDAO클래스의 selectCountMemo()메소드");
        return (int) mapper.queryForObject("selectCountMemo",item);
    }
 
    public ArrayList<GuestbookVO> selectListMemo(SqlMapClient mapper, Params params) throws SQLException {
        System.out.println("GuestbookDAO클래스의 selectListMemo()메소드");
        return (ArrayList<GuestbookVO>) mapper.queryForList("selectListMemo",params);
    }
    
    public int selectCountName(SqlMapClient mapper, String item) throws SQLException {
        System.out.println("GuestbookDAO클래스의 selectCountName()메소드");
        return (int) mapper.queryForObject("selectCountName",item);
    }
 
    public ArrayList<GuestbookVO> selectListName(SqlMapClient mapper, Params params) throws SQLException {
        System.out.println("GuestbookDAO클래스의 selectListName()메소드");
        return (ArrayList<GuestbookVO>) mapper.queryForList("selectListName",params);
    }
    
        public int selectCountNameMemo(SqlMapClient mapper, String item) throws SQLException {
            System.out.println("GuestbookDAO클래스의 selectCountNameMemo()메소드");
            return (int) mapper.queryForObject("selectCountNameMemo",item);
        }
        
        public ArrayList<GuestbookVO> selectListNameMemo(SqlMapClient mapper, Params params) throws SQLException {
            System.out.println("GuestbookDAO클래스의 selectListNameMemo()메소드");
            return (ArrayList<GuestbookVO>) mapper.queryForList("selectListNameMemo",params);
        }
}
 
cs
더보기

-Description

싱글톤패턴 클래스임

20 : InsertService 클래스에서 mapper와 테이블에 저장할 데이터가 저장된 
객체를넘겨받고 guestbook.xml 파일의 insert sql 명령을 실행하는 메소드.

22 : 첫인자인 "insert"는  guestbook.xml에서 insert태그의 id 임.

25 : SelectService 클래스에서 mapper를 넘겨받고 테이블에 저장된 전체 글의 갯수를 얻어옴

27 : queryForObject() : select sql 명령의 실행 결과가 1건일 때 사용=>Object타입의 데이터를 결과로 얻어온다.
queryForList() : select sql 명령의 실행 결과가 여러건일 경우 사용한다.=> List 타입의 데이터를 결과로 얻어온다.


30 : SelectService 클래스에서 mapper와 1페이지분량의 글의 시작 인덱스와 끝 인덱스가 저장된
HashMap객체를 넘겨 받고 , 테이블에 저장된 전체 글 중에서 1페이지 분량에 해당되는
 글 목록을 얻어오는  명령을 실행하는 메소드

35 : SelectService 클래스에서 mapper와 수정 또는 삭제할 글번호를 넘겨받고 
테이블에 저장된 글 1건을 얻어오는명령을 실행하는 메소드

40 : 특정 idx에 해당하는 게시글 삭제

45 : 게시글 내용을 수정하는 메소드

50 : 사용자 검색을 위한 메소드,
SelectService 클래스에서 mapper와 검색어내용을 넘겨받고 
테이블에 저장된 전체 글 중에서 검색어를 포함하는 글의 갯수를
얻어오는 메소드

55 : 사용자 검색을 위한 메소드,
SelectService 클래스에서 mapper와 Params을 넘겨받고 
테이블에서 Params에 해당하는 게시글들을 얻어오는 메소드

60,70 : 사용자 검색을 위해 게시글의 수를 얻어오는 메소드

65,75 : 사용자 검색을 위한 메소드

-insert.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <form action="insertOK.jsp" method="post">
        <table width="600" align="center" border="1" cellpadding="5" cellspacing="0"> 
            <tr>
                <th colspan="2">방명록 쓰기</th>
            </tr>
            <tr>
                <td width="100">이름</td>
                <td width="500"><input type="text" name="name"/></td>
            </tr>
            <tr>
                <td>비밀번호</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td>메모</td>
                <td><textarea row="10" cols="65" name="memo" style="resize: none;"></textarea></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="글남기기"/>
                    <input type="reset" value="다시쓰기"/>
                    <input type="button" value="돌아가기" onclick="history.back()"/>
                </td>
            </tr>
        </table>
    </form>
    
</body>
</html>
cs
더보기

-Description

View 부분

11 : submit 버튼 클릭시 , insertOK.jsp 로 이동,  name, password, memo가 request에 들어감.

-insertOK.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 import="com.koreait.service.InsertService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    request.setCharacterEncoding("UTF-8");
%>
 
<jsp:useBean id="vo" class="com.koreait.vo.GuestbookVO"> <!-- 객체생성 -->
    <jsp:setProperty property="*" name="vo"/>   <%-- vo객체의 setter가  전체로 수행됨 --%>
</jsp:useBean>
 
<%
    vo.setIp(request.getRemoteAddr());
    
    InsertService.getInstance().insert(vo);
    
    response.sendRedirect("list.jsp");
%>
 
 
 
</body>
</html>
cs
더보기

-Description

12 :  post 방식으로 데이터가 넘어올 때 한글 깨짐을 방지

15~17 : 넘어오는 데이터가 VO 클래스에 멤버로 존재하면 useBean으로 받고 존재하지 않으면 별도로 받아 VO클래스에 저장한다
useBean 액션 태그는 객체를 만들 때 사용한다. 
useBean 액션 태그의 id 속성에는 만들려 하는 객체의 이름을 쓴다.
useBean 액션 태그의 class 속성에는 객체를 만들려 하는 클래스 이름을 반드시 풀 패키지 이름과 같이 쓴다.

setProperty 액션 태그의 property 속성에는 setter 메소드를 실행할 멤버 변수의 이름을 쓴다.
setProperty 액션 태그의 name속성에는 setter 메소드가 작성된 클래스 객체의 이름을 쓴다.
setProperty 액션 태그를 사용하면 request.getParameter() 메소드로 넘어오는 데이터를 받지
않아도 jsp가 자동으로 받아준다.
 
아래  2문장과 같은 기능이 실행됨.
 String id = request.getParameter("id");
membervo.setId(id);
 
또한 Integer.parseInt(), Boolean.parseBoolean() 를 사용하지 않아도 자동으로 데이터가 변환되서 저장된다.

setProperty 액션 태그의 property 속성에 "*"을 입력하면 
form 의 name 속성에 입력한 이름과 같은 모든 멤버 변수의 setter가 실행된다. 

20 : getRemoteAddr() : 접속자 ip 주소를 받는다.

22 : 저장된 객체(vo)를 전처리 작업을 위해서 Service 클래스로
넘겨 sql 명령을 실행하기 전에 필요한 작업이 있으면 실행한다.

24 : 테이블에 글 1건을 저장했으므로 브라우저에 저장된 글을 출력하기 위해 1페이지 분량의 
글 목록을 얻어오는 페이지(list.jsp)로 넘겨준다

//VO 클래스 => 1건의 글을 저장하는 클래스
//List 클래스 => 1페이지 분량의 글 목록과 페이징 작업에 사용할 8개의 변수를 저장하는 클래스
//Service 클래스 => sql 명령을 실행하기 전에 전처리 작업을 실행하는 클래스
//DAO(Data Access Object) => xml 파일에서 정의한 sql 명령을 실행하는 클래스

-update.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
62
63
64
65
66
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  <!--  jstl을 이용해 대입문,제어문,서식,함수를 사용하기 위해 아래의 내용을 코딩한다. -->
<%@ 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"%><!-- 함수 -->
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<fmt:requestEncoding value="UTF-8"/>
 
    <form action="updateOK.jsp" method="post">
        <table width="600" align="center" border="1" cellpadding="%" cellspacing="0">
            <tr>
                <th colspan="2">삭제할 글 보기</th>
            </tr>
            <tr>
                <td width="100">이름</td>
                <td width="500">
                    <%-- <c:set var="name" value="${fn:replace(vo.name,'<','&lt;')}"/>
                    <c:set var="name" value="${fn:replace(name,'>','&gt;')}"/>
                    ${name} --%>
                    <input type="text" name="name" value="${fn:trim(vo.name)}" readonly="readonly"/>
                </td>
            </tr>
            <tr>
                <td>작성일</td>
                <td>
                    <fmt:formatDate value="${vo.writedate}" pattern="yyyy년 MM월 dd일 E요일" />
                </td>
            </tr>
            <tr>
                <td>메모</td>
                <td>
                    <%-- <c:set var="memo" value="${fn:replace(vo.memo,'<','&lt;')}"/>
                     <c:set var="memo" value="${fn:replace(memo,'>','&gt;')}"/>
                     <c:set var="memo" value="${fn:replace(memo,enter,'</br>')}"/>
                     ${memo} --%>
                     <textarea row="10" cols="65" name="memo" style="resize:none;">${vo.memo}</textarea>    
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <label>
                        비밀번호 <input type="password" name="password"/>
                        <input type="submit" value="수정하기"/>
                        <input type="reset" value="다시쓰기"/>
                        <input type="button" value="돌아가기" onclick="history.back()"/>
                    </label>
                </td>
            </tr>
        </table>
        
        <input type="hidden" name="idx" value="${vo.idx}">
        <input type="hidden" name="currentPage" value="${currentPage}">
        
    </form>
 
</body>
</html>
cs
더보기

-Description

View부분

삭제할 글을 화면에 표시하고 비밀번호를 입력받아 실제로 글을 삭제하는 페이지로 넘겨준다.

18 : form태그를 통해 updateOK.jsp 로 이동,  name,memo,password 그리고 idx,currentPage 들이 전달됨.

60,61 : 삭제할 글번호와 수정 후 돌아갈 페이지 번호를 form에 hidden
으로 저장해서 삭제하는 페이지로 넘겨줘야 한다. 

-updateOK.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 import="com.koreait.service.UpdateService"%>
<%@page import="com.koreait.service.DeleteService"%>
<%@page import="com.sun.xml.internal.bind.v2.runtime.Name"%>
<%@page import="com.koreait.vo.GuestbookVO"%>
<%@page import="com.koreait.service.SelectService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <% request.setCharacterEncoding("UTF-8");
       int currentPage= Integer.parseInt(request.getParameter("currentPage"));
    %>
<jsp:useBean id="vo" class="com.koreait.vo.GuestbookVO">
    <jsp:setProperty property="*" name="vo"/>
</jsp:useBean>
 
<%
String password=request.getParameter("password");
 
    GuestbookVO original = SelectService.getInstance().selectByIdx(vo.getIdx());
 
    out.println("<script>");
    if( original.getPassword().trim().equals(vo.getPassword() ) ){
        
        UpdateService.getinstance().update(vo);
        
        out.println("alert('"+vo.getIdx()+"번 글 삭제완료."+"')");
    }else{
        out.println("alert('비밀번호가 일치하지 않습니다.')");
    }
    out.println("location.href='list.jsp?currentPage="+currentPage+"'");
    out.println("</script>");
%>
 
</body>
</html>
cs

 

더보기

-Description

16~20 : update.jsp에서 넘어오는 데이터를 받는다. 
VO 클래스에 멤버로 존재하면 useBean으로 받고 나머지는 별도로 받는다.

25 : 삭제할 글의 비밀번호와 삭제하기 위해 입력한 비밀번호를 비교하기 위해
삭제할 글을 테이블에서 얻어온다.

//oracle은 필드의 데이터 타입을 char로 선언하면 필드의 자리수보다
//입력된 문자수가 적을 때 남는 자리가 모두 공백으로 리턴된다.
//해결법 1 . oracle의 필드 타입으로 char대신 varchar2를 사용하면
//남는자리가 공백으로 처리되지 않는다.
//해결법 2.  trim으로 처리해줘야한다.

27~37 : 삭제할 글의 비밀번호와 삭제하기 위해 입력한 비밀번호가 같으면 글을 삭제한다.

-UpdateService.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
package com.koreait.service;
 
import java.sql.SQLException;
 
import com.ibatis.sqlmap.client.SqlMapClient;
import com.koreait.dao.GuestbookDAO;
import com.koreait.ibatis.MyAppSqlConfig;
import com.koreait.vo.GuestbookVO;
 
public class UpdateService {
    private static UpdateService instance= new UpdateService();
    private UpdateService() {}
    public static UpdateService getinstance() {
        return instance;
    }
    
    public void update(GuestbookVO vo) {
        System.out.println("UpdateService클래스의 update() 메소드");
        SqlMapClient mapper= MyAppSqlConfig.getSqlMapInstance();
        try {
            GuestbookDAO.getinstance().update(mapper,vo);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 
cs
더보기

-Description

Singleton 패턴임

updateOK..jsp에서 수정할 정보가 저장된 객체를 넘겨받고 mapper를
얻어온 후 테이블에서 글 1건을 수정하는 DAO클래스의 update sql
명령을 실행.

-delete.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
62
63
64
65
66
67
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  <!--  jstl을 이용해 대입문,제어문,서식,함수를 사용하기 위해 아래의 내용을 코딩한다. -->
<%@ 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"%><!-- 함수 -->
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<!-- 삭제할 글을 화면에 표시하고 비밀번호를 입력받아 실제로 글을 삭제하는 페이지로 넘겨준다.-->
<fmt:requestEncoding value="UTF-8"/>
 
    <form action="deleteOK.jsp" method="post">
        <table width="600" align="center" border="1" cellpadding="%" cellspacing="0">
            <tr>
                <th colspan="2">삭제할 글 보기</th>
            </tr>
            <tr>
                <td width="100">이름</td>
                <td width="500">
                    <c:set var="name" value="${fn:replace(vo.name,'<','&lt;')}"/>
                    <c:set var="name" value="${fn:replace(name,'>','&gt;')}"/>
                    ${name}
                </td>
            </tr>
            <tr>
                <td>작성일</td>
                <td>
                    <fmt:formatDate value="${vo.writedate}" pattern="yyyy년 MM월 dd일 E요일" />
                </td>
            </tr>
            <tr>
                <td>메모</td>
                <td>
                    <c:set var="memo" value="${fn:replace(vo.memo,'<','&lt;')}"/>
                     <c:set var="memo" value="${fn:replace(memo,'>','&gt;')}"/>
                     <c:set var="memo" value="${fn:replace(memo,enter,'</br>')}"/>
                     ${memo}
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <label>
                        비밀번호 <input type="password" name="password"/>
                        <input type="submit" value="삭제하기"/>
                        <input type="reset" value="다시쓰기"/>
                        <input type="button" value="돌아가기" onclick="history.back()"/>
                    </label>
                </td>
            </tr>
        </table>
        
        <!--  삭제할 글번호와 삭제 후 돌아갈 페이지 번호를 form에 hidden
        으로 저장해서 삭제하는 페이지로 넘겨줘야 한다. -->
        <input type="hidden" name="idx" value="${vo.idx}">
        <input type="hidden" name="currentPage" value="${currentPage}">
        
    </form>
 
</body>
</html>
cs

 

-deleteOK.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
<%@page import="com.koreait.service.DeleteService"%>
<%@page import="com.sun.xml.internal.bind.v2.runtime.Name"%>
<%@page import="com.koreait.vo.GuestbookVO"%>
<%@page import="com.koreait.service.SelectService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <% request.setCharacterEncoding("UTF-8");
    //delete.jsp에서 넘어오는 데이터를 받는다. =>
    //VO 클래스에 멤버로 존재하면 useBean으로 받고 나머지는 별도로 받는다.
    int currentPage= Integer.parseInt(request.getParameter("currentPage"));
    %>
<jsp:useBean id="vo" class="com.koreait.vo.GuestbookVO">
    <jsp:setProperty property="*" name="vo"/>
</jsp:useBean>
 
<%
String password=request.getParameter("password");
//삭제할 글의 비밀번호와 삭제하기 위해 입력한 비밀번호를 비교하기 위해
//삭제할 글을 테이블에서 얻어온다.
    GuestbookVO original = SelectService.getInstance().selectByIdx(vo.getIdx());
    
    //oracle은 필드의 데이터 타입을 char로 선언하면 필드의 자리수보다
    //입력된 문자수가 적을  남는 자리가 모두 공백으로 리턴된다.
    //해결법 1 . oracle의 필드 타입으로 char대신 varchar2를 사용하면
    //남는자리가 공백으로 처리되지 않는다.
    //해결법 2.  trim으로 처리해줘야한다.
 
    out.println("vo.getPassword().length() : "+vo.getPassword().length()+"<br/>" );
    out.println("original.getPassword().length() : "+original.getPassword().length()+"<br/>" );
 
    //삭제할 글의 비밀번호와 삭제하기 위해 입력한 비밀번호가 같으면 글을 삭제한다.
    out.println("<script>");
    if( original.getPassword().trim().equals(vo.getPassword() ) ){
        
        DeleteService.getinstance().delete(vo.getIdx());
        
        out.println("alert('"+vo.getIdx()+"번 글 삭제완료."+"')");
    }else{
        out.println("alert('비밀번호가 일치하지 않습니다.')");
    }
    out.println("location.href='list.jsp?currentPage="+currentPage+"'");
    out.println("</script>");
%>
 
</body>
</html>
cs

-DeleteService.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
package com.koreait.service;
 
import java.sql.SQLException;
 
import com.ibatis.sqlmap.client.SqlMapClient;
import com.koreait.dao.GuestbookDAO;
import com.koreait.ibatis.MyAppSqlConfig;
 
//Singleton
public class DeleteService {
    private static DeleteService instance= new DeleteService();
    private DeleteService() {}
    public static DeleteService getinstance() {
        return instance;
    }
    
    //deleteOK.jsp에서 삭제할 글번호를 넘겨 받고 mapper를 얻어온 후
    //테이블에서 글 1건을 삭제하는 DAO 클래스의 delete sql 명령을 
    //실행하는 메소드를 실행하는 메소드
    public void delete(int idx) {
        System.out.println("DeleteService클래스의 delete() 메소드");
        SqlMapClient mapper= MyAppSqlConfig.getSqlMapInstance();
        try {
            GuestbookDAO.getinstance().delete(mapper,idx);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 
cs

GUI- 검색부분은 업데이트예정

-요약-

 

-마침글-

.

'21년이전 > 국비-JSP+oracle' 카테고리의 다른 글

JSP+Oracle-MVC패턴게시판  (0) 2021.04.16
JSP+Oracle-Freeboard  (0) 2021.04.13
JSP+Oracle - Category  (0) 2021.04.07

+ Recent posts