내가 이해한 한도내에서의 스프링에서의 ajax 구현시 데이터 흐름도는

1. ajax 함수 호출 



2.  - ajax함수내에서 데이터 조회에 참조할 데이터변수
     - 요청주소(컨트롤러에 맵핑해서 실행할 url 주소) 설정



3. 2번항목에서 지정한 컨트롤러에 실행되는 메소드내에서는 getParameter로 해당 변수를 받아온 후
    해당 변수를 사용하여 쿼리를 날려 결과값을 setAttribute 를 사용하여 jsp 단으로 전달한다. (return "abc.jsp";)



4. jsp에서는
        - 
responseText 인 경우 예를 들어
        <%  String result = (String) request.getAttribute("result");  out.write(result);         %>

과 같은 처리.

  - responseXML 인 경우

ArrayList<자료형> abc = (캐스팅 변환)request.getAttribute("속성명");

형대로 받아 StringBuilder를 사용해서 XML 형대로 문자열을 누적 처리.

다만, jsp에서 XML 형태로 가공할때 가공 후 응답은 

response.setContentType("text/xml; charset=euc-kr");

response.getWriter().write(result.toString()); 

을 사용하여 리턴.

EX) 간단한 XML 형태

<?xml version="1.0" encoding="utf-8"?>
<users>
<user>
<name>HyunWook Kim</name>
</user>
<user>
<name>redccoma</name>
</user>
</users>



5.    out.write(result) 구문이 실행되면 ajax 관련 함수중 콜백 함수를 실행하면서 응답확인을 하고 에러검출이 안될 경우

지정한 액션 혹은 지정한 함수를 실행. 예를 들어 xmlReq.status == 200 과 같은 조건일 경우 정상응답이므로 해당 조건하에서

사용자 정의 액션처리를 바로 하거나 printData(); 와 같은 사용자 지정함수를 호출.



6. printData() 와 같은 함수를 호출한다고 가정할 경우 var result = xmlReq.responseText; 

   혹은 var result = xmlReq.responseXML;  형태로 결과 데이터를 저장.

   당연히 TEXT와 같은 경우 단일 데이터이므로 재처리할 필요 없이 원하는 액션처리를 하면 되고,

   XML의 경우 아래의 코드처럼 xml값을 분석하여 가져온 후 동적으로 html 소스생성하고 innerHTML을 통해 문서로

   최종반환하여 처리를 종료.


  ex) 간단한 XML 분석 및 HTML 동적 소스 생성

var users = result.getElementsByTagName("user");

for(var i=0;i<users.length;i++){

result += users[i].getElementsByTagName("name")[0].firstChild.nodeValue + "<br>";

}

document.getElementById("str").innerHTML = str;


아래 영문내용과는 다르게 구현된 AJAX 소스 (어차피 같은 의미임-.-)

//AjaxSend02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


//전역변수

var xmlReq; 

//전송 역할 함수

function myFunc() {

var data = document.getElementById("data");

//ajax 객체

xmlReq = new XMLHttpRequest(); //IE 7.0 이상

//서버 요청주소

var url = "AjaxReceive02.jsp";

//서버요청시 데이터 전송하는 부분

//데이터가 두개 이상인 경우는

//식별자=값&식별자=값&.... 형태로 작성

var postString = "data=" + data.value;

//응답이 돌아온다면 callback 함수 호출

//이벤트 등록 부분

xmlReq.onreadystatechange = callBack;

//ajax 요청 형식 // true는 비동기

xmlReq.open("POST", url, true);

//전송하는 데이터 안에 한글이 있는 경우 인코딩방식을 알려주어야 함.

xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=euc-kr");

//ajax 요청

xmlReq.send(postString);

}

//응답 확인 함수

function callBack() {

//state는 1, 2, 3, 4의 총 4가지 상태가 있음.

//1은 요청전

//2는 요청후

//3은 서버로 응답을 보낸 상태

//4는 최종 응답을 받은 상태를 의미

if(xmlReq.readyState == 4) {

//status는 서버 응답의 종류를 의미

//200은 정상적인 처리가 되었음을 의미

//500은 JSP 실행은 했지만 오류가 발생함.

//404는 요청 주소에 해당하는 파일이 없음.

if(xmlReq.status == 200) {

//정상적인 응답을 화면에 출력하는 함수 호출

printData();

} else {

alert("처리 불가!");

}

}

}

//결과 출력 함수

function printData() {

//응답은 두가지 종류가 존재

//responseText, responseXML

var result = xmlReq.responseText;

//alert(result);

var msg = document.getElementById("msg");

msg.innerHTML = result;

}


</script>

</head>

<body>

<div>

<h2>데이터 송수신 테스트2(ajax 방식)</h2>

<form>

이름 <input type="text" name="name" id="name"><br>

전화번호 <input type="text" name="tel" id="tel"><br>

아이디 <input type="text" name="data" id="data"><br>

<input type="button" value="중복체크" onclick="myFunc()">

</form>

<div>결과 데이터 : <span id="msg"></span></div>

</div>

</body>

</html>




//AjaxReceive02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%


String data = request.getParameter("data");

String result = "OK";

if(data.equals("test") || data.equals("admin") || data.equals("hong")) {

result = "Cancel";

}


//ajax 방식에서 데이터를 처리후 재전송할때 out.write(값); 을 사용해야 함.

out.write(result);

%>



JSPAndAJAXExamples


Example 1 - Server side JSP encoding

service.jsp:

  <%@page contentType="text/html; charset=UTF-8"%>
 
<%@page import="org.json.simple.JSONObject"%>
 
<%
   
JSONObject obj=new JSONObject();
    obj
.put("name","foo");
    obj
.put("num",new Integer(100));
    obj
.put("balance",new Double(1000.21));
    obj
.put("is_vip",new Boolean(true));
    obj
.put("nickname",null);
   
out.print(obj);
   
out.flush();
  %>

Please note that you need to place json_simple-1.1.jar in WEB-INF/lib before running the JSP. Then the client side will get the resulting JSON text.

Example 2 - Client side XMLHttpRequest

client.html:

<html>
<head>
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<script type="text/javascript">
function createXMLHttpRequest(){
 
// See http://en.wikipedia.org/wiki/XMLHttpRequest
 
// Provide the XMLHttpRequest class for IE 5.x-6.x:
 
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
   
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
   
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
   
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
   
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
   
throw new Error( "This browser does not support XMLHttpRequest." )
 
};
 
return new XMLHttpRequest();
}

var AJAX = createXMLHttpRequest();

function handler() {
 
if(AJAX.readyState == 4 && AJAX.status == 200) {
     
var json = eval('(' + AJAX.responseText +')');
      alert
('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance);
 
}else if (AJAX.readyState == 4 && AJAX.status != 200) {
    alert
('Something went wrong...');
 
}
}

function show(){
  AJAX
.onreadystatechange = handler;
  AJAX
.open("GET", "service.jsp");
  AJAX
.send("");
};
</script>

<body>
 
<a href="#" onclick="javascript:show();"> Click here to get JSON data from the server side</a>
</html>

Please place client.html and service.jsp (see Example 1) in the same directory and then open client.html in IE or Firefox, click the link and you'll get result.



출처 : https://code.google.com/p/json-simple/wiki/JSPAndAJAXExamples


WRITTEN BY
빨강꼬마

,




WRITTEN BY
빨강꼬마

,

폼 객체

 

1. text 객체

 

주요 메서드와 속성

설명

name

텍스트 박스의 이름

value

텍스트 박스의 값

 

WebContent/form/text.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>text.html</title>

<script>

function copyFunc(ff){

ori = ff.ori.value;

ff.copy.value = ori;

}

</script>

</head>

<body>

<h1>text 입력상자의 값 제어</h1>

<form name='frm'>

원본 : <input type='text' name='ori' value='park'><br>

사본 : <input type='text' name='copy' value=''>

<p>

<input type='button' value='copy' onclick='copyFunc(this.form)'>

</form>

</body>

</html>

 

[실행결과]

 

2. radio 객체

 

주요 메서드와 속성

설명

form

체크 박스 입력 양식을 포함하는 폼 객체의 정보를 가져옴.

checked

체크 박스를 선택하도록함.

defaultChecked

체크 속성이 설정되었는지 확인

name

체크 박스의 이름

value

체크 박스의 값

type

type속성값을 제어

blur() focus()

포커스를 제어

click()

체크 박스를 체크함.

 

WebConent/form/radio.html

 

<html>

<head>

<title>라됴객체 </title>

<script language="JavaScript">

function mclick(f){

l=f.chk.length

for(i=; i < l ; ++i){

if(f.chk[i].checked){

f.re.style.backgroundColor=f.chk[i].value

f.re.value=f.chk[i].value}

}

}

</script>

</head>

<body>

<form name=ff>

<table border=0>

<th><center>Box의 색상을 고르시요</center></th>

<tr>

<td>

<textarea name=re rows=cols=30 ></textarea>

</td></tr><tr>

<td>

<input type="radio" name=chk value="#330000">검정

<input type="radio" name=chk value="#3300FF">파랑

<input type="radio" name=chk value="#00FF00">녹색

<input type="radio" name=chk value="#FF0000">빨강<br>

<input type="radio" name=chk value="#FFFF00">노랑

<input type="radio" name=chk value="#FFFFFF">흰색

<input type="radio" name=chk value="#FF9900">오랜지

<input type=button name=bu value="click" onclick="mclick(this.form)">

</td>

</tr>

</table>

</form>

</body>

</html>

 

 

 

3. checkbox 객체

 

주요 메서드와 속성

설명

form

체크 박스 입력 양식을 포함하는 폼 객체의 정보를 가져옴.

checked

체크 박스를 선택하도록함.

defaultChecked

체크 속성이 설정되었는지 확인

name

체크 박스의 이름

value

체크 박스의 값

type

type속성값을 제어

blur() focus()

포커스를 제어

click()

체크 박스를 체크함.

 

WebContent/form/checkbox2.html

 

<html>

<head>

<title> Check Box2 </title>

<script language="JavaScript">

function mclick(f){

l=f.chk.length

f.re.value=""

for(i=; i<l ; i++){

if(f.chk[i].checked) {f.re.value=f.re.value + f.chk[i].value + "\n"}

}

}

</script>

</head>

<body>

<form name="ff" method="post">

<table border=0>

<th>마음에 드는 연예인을 고르시요</th>

<tr>

<td>

<textarea name=re rows=cols=30 ></textarea>

</td></tr><tr>

<td>

<input type="checkbox" name=chk value="황수정">황수정

<input type="checkbox" name=chk value="채림">채림

<input type="checkbox" name=chk value="황신혜">황신혜

<input type="checkbox" name=chk value="김미화">김미화<br>

<input type="checkbox" name=chk value="이영자">이영자

<input type="checkbox" name=chk value="고두심">고두심

<input type="checkbox" name=chk value="신지">신지<br>

<input type=button name=bu value="선택" onclick="mclick(this.form)">

<input type=reset value="취소">

</td>

</tr>

</table>

</form>

</body>

</html>

 

 

 

4. select 객체

 

1) 객체명.selectedIndex : 선택한 항목의 번호(0번부터)

2) 객체명.[객체명.options.selectedIndex].value : 선택한 항목의 값.

3)객체명.[객체명.options.selectedIndex].text : 선택한 항목의 text.

 

WebContent/form/select.html

 

<HTML>

<HEAD>

<title> </title>

<script language="JavaScript">

function mclick(f,n){

f.tt.style.backgroundColor=n

}

function chang(f){

f.tt.style.backgroundColor=f.sel.options[f.sel.options.selectedIndex].value

}

</script>

</HEAD>

<BODY>

<b><h3>Select 를 이용하여 바탕 색상 바꾸기</h3></b><p>

<form name="ff">

<input type=text name=tt >

<select name="sel" onChange="chang(this.form)">

<option value="#000000">검은색

<option value="#006600">녹색

<option value="#00FF00">연두색

<option value="#FF0000">뻘건색

<option value="#FFFFFF">흰색

</select>

<input type="button" value="white" onClick="mclick(this.form, 'white')">

</form>

</BODY>

</HTML>

 

 

 

 

5. reset 버튼 객체

 

각 항목의 값을 초기값으로 셋팅한다.

특정항목에 값이 있을때 reset 되지 않도록 제어하는 예제임.

 

WebContent/form/onReset.html

<HTML>

<HEAD>

<TITLE>onReset()-1</TITLE>

<style>

input{font-size:40;}

</style>

<script>

function fun(ff)

{

if(ff.irum.value ==""return true;

else return false;

}

</script>

</HEAD>

<BODY>

<h3> 이름 항목에 값이 있으면 리셋버튼의 기능 중지</h3>

<form name="frm" onReset="return fun(this)">

Name <input type="text" name="irum" value=""><br>

Address <input type="text" name="addre" value=""><br>

<input type=reset value="다시">

</form>

</BODY>

</HTML>

 

[실행결과]

 

 

 

 

6. onSubmit 버튼

 

폼에 있는 정보를 서버로 전달하는 기능


WRITTEN BY
빨강꼬마

,

document.oncontextmenu = new Function('return false');   // 우클릭방지

document.ondragstart = new Function('reutrn false');        // 드래그 방지

document.onselectstart = new Function('return false');      // 복사 방지


WRITTEN BY
빨강꼬마

,

EX)

페이지 내에서 키보드 키를 누를 경우 실행하는 함수 지정

document.onkeydown = keyControl;


예제 함수

function keyControl() {

if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 17 || event.keyCode == 18 ||

event.keyCode == 112 || event.keyCode == 113 || event.keyCode == 114 || event.keyCode == 115 ||

event.keyCode == 116 || event.keyCode == 117 || event.keyCode == 118 || event.keyCode == 119 ||

event.keyCode == 120 || event.keyCode == 121 || event.keyCode == 122 || event.keyCode == 123 ||

event.keyCode == 91 || event.keyCode == 92) {

alert ("특수키 사용은 불가능합니다.");

return false;

}

}


←(백스패이스) = 8
TAB = 9
ENTER = 13
SHIFT = 16
CTRL = 17
ALT = 18
PAUSEBREAK = 19
CAPSLOOK = 20
한/영 = 21
한자 = 25
ESC = 27

스패이스 = 32
PAGEUP = 33
PAGEDN = 34
END = 35
HOME =36

←(중간) = 37
↑(중간) = 38
→(중간) = 39
↓(중간) = 40

0 = 48
1 = 49
2 = 50
3 = 51
4 = 52
5 = 53
6 = 54
7 = 55
8 = 56
9 = 57
INSERT = 45
DELETE = 46

A = 65
B = 66
C = 67
D = 68
E = 69
F = 70
G = 71
H = 72
I = 73
J = 74
K = 75
L = 76
M = 77
N = 78
O = 79
P = 80
Q = 81
R = 82
S = 83
T = 84
U = 85
V = 86
W = 87
X = 88
Y = 89
Z = 90

윈도우(왼쪽) = 91
윈도우(오른쪽) = 92
기능키 = 93
0(오른쪽) = 96
1(오른쪽) = 97
2(오른쪽) = 98
3(오른쪽) = 99
4(오른쪽) = 100
5(오른쪽) = 101
6(오른쪽) = 102
7(오른쪽) = 103
8(오른쪽) = 104
9(오른쪽) = 105
.(오른쪽) = 110
/(오른쪽) = 111
*(오른쪽) = 106
+(오른쪽) = 107
-(오른쪽) = 109
F1 = 112
F2 = 113
F3 = 114
F4 = 115
F5 = 116
F6 = 117
F7 = 118
F8 = 119
F9 = 120
F10 = 121
F11 = 122
F12 = 123
NUMLOCK = 144
SCROLLLOCK = 145
=(중간) = 187
-(중간) = 189
`(왼쪽콤마) = 192
(중간) = 220

[출처] event.keyCode 표|작성자 세봉



WRITTEN BY
빨강꼬마

,

-------------------------------------

상담 게시판 (Spring, iBatis 버전)


1. 웹 상에서 글쓰기, 글보기를 할 수 있는 프로그램.


2. 회원, 비회원 글쓰기 가능. 회원 댓글 쓰기. 회원 가입. 회원 로그인, 로그아웃.


3. 관리자 관리 기능. 관리자 답변글 쓰기.


4. 프로젝트 생성 (ConsultationSpring_20121228)


-------------------------------------

--상담게시판 테이블 (글번호, 글쓴이이름, 패스워드, 제목, 내용, 작성일)


CREATE TABLE consultation (

sid NUMBER  --PK 지정. 시퀀스 지원.

,name NVARCHAR2(20)

,pw VARCHAR2(20) --암호화 지원

,title NVARCHAR2(100)

,content NVARCHAR2(2000)

,wdate DATE --자동 입력. 시스템 현재 날짜.

);


ALTER TABLE consultation

ADD CONSTRAINT consultation_sid_pk PRIMARY KEY(sid);


CREATE SEQUENCE consultationSeq;


INSERT INTO consultation (sid, name, pw, title, content, wdate)

VALUES (consultationSeq.nextVal

,'관리자'

,encrypt('1234', '관리자')  --사용자 정의 암호화 함수

,'상담 게시판이 오픈되었습니다'

,'많은 이용 바랍니다'

,SYSDATE);

COMMIT;


SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

ORDER BY sid DESC;


--SID 기준 검색 쿼리

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

FROM consultation 

WHERE sid=1;


SELECT sid, title, content

FROM consultation 

WHERE sid=1 AND name='관리자' AND pw=encrypt('1234', '관리자');



--이름 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;


--제목 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(title) LIKE '%'||LOWER('html')||'%'

ORDER BY sid DESC;


--내용 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(content) LIKE '%'||LOWER('html')||'%'

ORDER BY sid DESC;




--페이지 처리 쿼리문 (총 게시물 카운트)

SELECT COUNT(*) AS count FROM consultation;



--페이지 처리 쿼리문 (특정 페이지 게시물 읽어오기. 시작번호, 끝번호 필요)

--> 한 페이지당 10개의 게시물 처리

--> 1페이지 게시물은 시작번호 1 ~ 끝번호 10

--> 2페이지 게시물은 시작번호 11 ~ 끝번호 20

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation

ORDER BY sid DESC) data)

WHERE rnum>=1 AND rnum<=10;


CREATE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation

ORDER BY sid DESC) data);


SELECT * 

FROM pageListView

WHERE rnum>=1 AND rnum<=10;




-----------------------------------------------------------

--관리자 답변글 전용 테이블

CREATE TABLE consultReply (

rid NUMBER  --PK

,name NVARCHAR2(20) --관리자 전용

--,pw VARCHAR2(20)  --관리자 전용이므로 패스워드 저장 안함

,title NVARCHAR2(100)

,content NVARCHAR2(2000)

,wdate DATE

);


ALTER TABLE consultReply

ADD CONSTRAINT consultReply_rid_pk PRIMARY KEY(rid);


CREATE SEQUENCE consultReplySeq;


--답변글과 부모글 연관성 지정 필요

--> 부모글 테이블에 답변글 번호를 저장하는 컬럼 추가 및 FK 지정

ALTER TABLE consultation

ADD rid NUMBER;

ALTER TABLE consultation

ADD CONSTRAINT consultation_rid_fk FOREIGN KEY (rid)

REFERENCES consultReply(rid);


--답변글 추가 쿼리

INSERT INTO consultReply (rid, name, title, content, wdate)

VALUES (consultReplySeq.nextval, '관리자', '예약 확인했습니다.'

,'내일 오전 중으로 연락 드리겠습니다.', SYSDATE);

COMMIT;


--특정 부모글에 답변글 번호를 연결하는 쿼리

UPDATE consultation

SET rid=consultReplySeq.currval

WHERE sid=49;

COMMIT;


--답변글 번호도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid  --답변글 번호 추가

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid  --답변글 번호 추가

FROM consultation 

WHERE sid=1;


--답변글 번호도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid  --답변글 번호 추가

FROM consultation

ORDER BY sid DESC) data);


--답변글 읽어오는 쿼리(RID 필요)

SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

FROM consultReply

WHERE rid=1;


----------------------------------------------------

회원 가입, 로그인, 로그아웃 쿼리 작성


--회원 테이블 작성

CREATE TABLE jmember (

id VARCHAR2(20) --PK

,pw VARCHAR2(20) --암호화 지원

,name NVARCHAR2(20)

,email VARCHAR2(100)

,tel VARCHAR2(30)

,wdate DATE

,grade NUMBER DEFAULT 4 --관리자 1, 직원 2, 학생 3, 회원가입 4

);


ALTER TABLE jmember

ADD CONSTRAINT jmember_id_pk PRIMARY KEY(id);


--관리자 전용 입력 쿼리

INSERT INTO jmember (id, pw, name, email, tel, wdate, grade)

VALUES ('admin', encrypt('1234', 'admin'),'관리자', 'admin@test.com', '02-123-1234', SYSDATE, 1);

COMMIT;


--사용자 입력 쿼리 (회원등급이 자동으로 회원가입(4) 등급이 된다)

INSERT INTO jmember (id, pw, name, email, tel, wdate)

VALUES ('test', encrypt('1234', 'test'),'테스트'

, 'test@test.com', '02-111-1111', SYSDATE);

COMMIT;


--회원 확인용 쿼리 (id, pw 동시 검사)

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade

FROM jmember

WHERE id='admin' AND pw=encrypt('1234', 'admin');


--회원 확인용 쿼리 (id만 검사)

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade

FROM jmember

WHERE id='admin';



--패스워드 수정 쿼리

UPDATE jmember 

SET pw=encrypt('새로운패스워드', '아이디')

WHERE pw=encrypt('기존패스워드', '아이디')

AND id='아이디';



--회원 정보 수정 쿼리

UPDATE jmember 

SET name='새로운이름', email='새로운이메일', tel='새로운전화번호'

WHERE pw=encrypt('기존패스워드', '아이디')

AND id='아이디';



-----------------------------------------------------------

--댓글 저장용 테이블 생성

CREATE TABLE consultComment (

cid NUMBER --PK. 댓글 번호

,id VARCHAR2(20) -- 글쓴이의 아이디

,name NVARCHAR2(20) --글쓴이의 이름

,title NVARCHAR2(200)

,wdate DATE

,sid NUMBER --FK. 부모 글번호

);


ALTER TABLE consultComment

ADD CONSTRAINT consultComment_cid_pk PRIMARY KEY(cid);


ALTER TABLE consultComment

ADD CONSTRAINT consultComment_sid_fk FOREIGN KEY (sid)

REFERENCES consultation(sid);


--댓글 추가 여부를 확인할 수 있는 컬럼을 부모 테이블에 추가

ALTER TABLE consultation

ADD commentCount NUMBER DEFAULT 0;


CREATE SEQUENCE consultCommentSeq;


--댓글 입력 (댓글 테이블에 댓글 내용 추가)

INSERT INTO consultComment (cid, id, name, title, wdate, sid)

VALUES (consultCommentSeq.nextval, 'hong', '홍길동', '댓글 테스트', SYSDATE, 1);

COMMIT;


--댓글 입력 (부모 테이블에 댓글 갯수 증가)

UPDATE consultation

SET commentCount = commentCount + 1

WHERE sid=1;

COMMIT;



--댓글 출력(부모글 기준)

SELECT cid, id, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultComment

WHERE sid=1

ORDER BY cid ASC;



--댓글 갯수도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount --댓글 갯수

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid

,commentCount --댓글 갯수

FROM consultation 

WHERE sid=1;



--댓글 갯수도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount --댓글 갯수

FROM consultation

ORDER BY sid DESC) data);



--댓글 삭제 쿼리

DELETE 

FROM consultComment

WHERE cid=1 AND id='hong';




-----------------------------------------------------------

회원 전용 글쓰기 과정 추가


--회원 전용 글쓰기를 위해서 consultation 테이블에 id 컬럼 추가

ALTER TABLE consultation

ADD id VARCHAR2(20);


--글쓰기 내용을 입력하는 과정에서 ID 추가

INSERT INTO consultation (sid, name, pw, title, content, wdate, id)

VALUES (consultationSeq.nextVal

,'관리자'

,encrypt('1234', '관리자')  --사용자 정의 암호화 함수

,'상담 게시판이 오픈되었습니다'

,'많은 이용 바랍니다'

,SYSDATE

, 'hong');

COMMIT;



--아이디도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount

,id --아이디

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid

,commentCount

,id --아이디

FROM consultation 

WHERE sid=1;



--아이디도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount

,id --아이디

FROM consultation

ORDER BY sid DESC) data);



------------------------------------------------------------

//ConsultationController.java -> 컨트롤러 클래스.


//ConsultationDTO.java


//consultationIbatis.xml


//common.css, table.css -> CSS 전용 파일.


//consultList.jsp -> 글목록 페이지. JSTL, EL 표현 사용.


//consultInsertForm.jsp -> 글 입력 페이지


//consultation.js -> 자바스크립트 전용 파일.


//consultView.jsp -> 글 내용 보기 페이지


//consultPW.jsp -> 패스워드 검사 페이지


//consultModifyForm.jsp -> 글 수정 페이지


//MyUtil.java -> 페이징 처리 전용 메소드 


//adminReplyForm.jsp -> 관리자 답변글 쓰기 전용 페이지


//MemberDTO.java


//memberIbatis.xml


//MemberController.java -> 회원 관리 전용 컨트롤러 클래스


//login.jsp -> 로그인 화면용 페이지


//memberInfo.jsp -> 회원 정보 출력용 페이지


//mainMenu.jsp -> 주메뉴 전용 페이지


//consultMemberInsertForm.jsp -> 회원 전용 글쓰기 페이지


//memberInsertForm.jsp -> 회원 가입 화면용 페이지


//memberIDCheck.jsp -> Ajax를 이용한 아이디 중복 체크 페이지


//memberInsertOK.jsp -> 회원 가입 완료 메시지 페이지


//memberInsertCancel.jsp -> 회원 가입 실패 메시지 페이지


//memberList.jsp -> 회원 명단 출력 페이지 (관리자, 직원 전용)


//adminUpdateForm.jsp -> 회원 수정 페이지 (관리자 전용)


//memberPWModifyForm.jsp -> 패스워드 수정 페이지(사용자)


//memberModifyForm.jsp -> 회원 수정 페이지 (사용자)


//sqlMapConfig.xml -> iBatis XML 파일 등록


//요청주소

http://localhost:8090/ConsultationSpring_20121228/consultList.mvc


-------------------------------



WRITTEN BY
빨강꼬마

,

-----------------------------------------

회원관리+성적처리 프로젝트 (Spring, iBatis 버전)


1. 성적 테이블, 회원 테이블 조인. FK 설정 필요.


2. 회원(회원번호-PK, 이름, 전화번호) -> 이전과 동일


3. 성적 (성적번호-PK, 회원번호-FK, 국어, 영어, 수학) 

-> 이름 대신 회원번호-FK 설정


4. 회원에 회원 등록을 먼저하고, 성적에 성적 입력을 나중에 한다.


5. 입력, 출력, 수정, 삭제 기능을 모두 구현할 것.


----------------------------------------

CREATE TABLE member2 (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member2

ADD CONSTRAINT member2_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE member2Seq;


//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'hong', '111-1111');

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'park', '222-2222');

COMMIT;



--성적 등록 여부 확인용 쿼리

SELECT mid, name, tel

, (SELECT COUNT(*) FROM score2 WHERE mid=m.mid) AS count 

FROM member2 m 

ORDER BY mid;


----------------------------------------

CREATE TABLE score2 (

sid NUMBER --PK, 자동 번호 부여

,mid NUMBER --FK

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score2

ADD CONSTRAINT score2_sid_pk PRIMARY KEY (sid);

ALTER TABLE score2

ADD CONSTRAINT score2_kor2_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mat_ck CHECK (mat BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mid_fk FOREIGN KEY (mid)

REFERENCES member2(mid);



--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE score2Seq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score2 (sid, mid, kor, eng, mat)

VALUES (score2Seq.nextval, 1, 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+)


--SELECT 쿼리 전용 뷰 생성(scott 계정)

CREATE OR REPLACE VIEW member2Score2View

AS

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+);


--뷰를 이용한 SELECT 쿼리 실행

SELECT mid, sid, name, kor, eng, mat, tot, ave, grade 

FROM member2Score2View;


----------------------------------------------

//MemberDTO.java -> 회원 정보 저장용 클래스


//ScoreDTO.java  -> 성적 정보 저장용 클래스


//memberScoreIbatis.xml -> iBatis용 쿼리 객체 저장소


//sqlMapConfig.xml -> 데이터베이스 연결 정보 지정, iBatis XML 파일 등록.


//MemberController.java -> 컨트롤러클래스. 데이터베이스 액세스 전용 클래스


//ScoreController.java -> 컨트롤러클래스. 데이터베이스 액세스 전용 클래스


//BasicStyle.css


//memberList.jsp -> JSTL, EL 표현으로 대체


//memberInsertForm.jsp


//memberUpdateForm.jsp -> JSTL, EL 표현으로 대체


//scoreList.jsp -> JSTL, EL 표현으로 대체


//scoreInsertForm.jsp


//scoreUpdateForm.jsp -> JSTL, EL 표현으로 대체


//요청주소

http://localhost:8090/MemberScore_Spring_20121227/memberList.mvc


----------------------------------------------

//MemberDTO.java -> 회원 정보 저장용 클래스

package com.test;


public class MemberDTO {

private String mid;

private String name, tel;

//성적이 등록된 상태인지 확인하기 위한 변수 추가

private int count; 

public int getCount() {

return count;

}

public void setCount(int count) {

this.count = count;

}


public String getMid() {

return mid;

}

public void setMid(String mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}





//ScoreDTO.java  -> 성적 정보 저장용 클래스

package com.test;


public class ScoreDTO {

//null 데이터 처리를 위해서 멤버변수의 자료형을 String으로 처리함.

private String mid, sid; //추가

private String name;

private String kor, eng, mat;


private String tot;

private String ave;

private String grade;

//추가

public String getMid() {

return mid;

}

public void setMid(String mid) {

this.mid = mid;

}

public String getSid() {

return sid;

}

public void setSid(String sid) {

this.sid = sid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getKor() {

return kor;

}

public void setKor(String kor) {

this.kor = kor;

}

public String getEng() {

return eng;

}

public void setEng(String eng) {

this.eng = eng;

}

public String getMat() {

return mat;

}

public void setMat(String mat) {

this.mat = mat;

}

public String getTot() {

return tot;

}

public void setTot(String tot) {

this.tot = tot;

}

public String getAve() {

return ave;

}

public void setAve(String ave) {

this.ave = ave;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}


}





//memberScoreIbatis.xml -> iBatis용 쿼리 객체 저장소

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="mySql">


<!-- 자주 사용하는 클래스에 대한 별칭 지정 가능 -->

<typeAlias alias="memberDTO" type="com.test.MemberDTO"/>

<typeAlias alias="scoreDTO" type="com.test.ScoreDTO"/>

<insert id="addMember" parameterClass="memberDTO">

INSERT INTO member2 (mid, name, tel) 

VALUES (member2Seq.nextval, #name#, #tel#)

</insert>

<select id="countMember" resultClass="Integer">

SELECT COUNT(*) AS count FROM member2

</select>

<select id="listsMember" resultClass="memberDTO">

SELECT mid, name, tel, (SELECT COUNT(*) FROM score2 WHERE mid=m.mid) AS count FROM member2 m ORDER BY mid

</select>

<delete id="removeMember" parameterClass="String">

DELETE member2 WHERE mid=#mid#

</delete>

<select id="searchMember" parameterClass="String" resultClass="com.test.MemberDTO" >

SELECT mid, name, tel FROM member2 WHERE mid=#mid#

</select>

<update id="modifyMember" parameterClass="com.test.MemberDTO">

UPDATE member2 SET name=#name#, tel=#tel# WHERE mid=#mid#

</update>

<insert id="addScore" parameterClass="scoreDTO">

INSERT INTO score2 (sid, mid, kor, eng, mat)

VALUES (score2Seq.nextval, #mid#, #kor#, #eng#, #mat#)

</insert>

<select id="listsScore" resultClass="com.test.ScoreDTO">

SELECT mid, sid, name, kor, eng, mat, tot, ave, grade 

FROM member2Score2View

</select>

<delete id="removeScore" parameterClass="String">

DELETE score2 WHERE mid=#mid#

</delete>

<select id="searchScore" parameterClass="String" resultClass="com.test.ScoreDTO">

SELECT kor, eng, mat FROM score2 WHERE mid=#mid#

</select>

<update id="modifyScore" parameterClass="com.test.ScoreDTO">

UPDATE score2 SET kor=#kor#, eng=#eng#, mat=#mat# WHERE mid=#mid#

</update>


</sqlMap>





//sqlMapConfig.xml -> 데이터베이스 연결 정보 지정, iBatis XML 파일 등록.

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMapConfig      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">


<sqlMapConfig>


  <settings

    cacheModelsEnabled="false"

    useStatementNamespaces="true"/>


  <sqlMap resource="com/spring/dao/sqlMap/memberScoreIbatis.xml"/>

  

  

</sqlMapConfig>





//MemberController.java -> 컨트롤러클래스. 데이터베이스 액세스 전용 클래스

package com.test;


import java.util.ArrayList;

import java.util.List;


import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


import com.spring.dao.CommonDAO;


@Controller("memberController")

public class MemberController {


//iBatis 연결 객체인 IBatisDaoImpl 클래스를 dao 변수와 연결시킨다.

@Resource(name="dao")

private CommonDAO dao;

@RequestMapping(value="/memberList.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String memberList(MemberDTO dto, HttpServletRequest req) {

try {

List<Object> arrayList = dao.getListData("mySql.listsMember");

req.setAttribute("arrayList", arrayList);

} catch (Exception e) {

System.out.println(e.toString());

}

return "memberList.jsp";

}

@RequestMapping(value="/memberInsertForm.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String memberInsertForm() {

//forward() 메소드 역할

return "memberInsertForm.jsp";

}

@RequestMapping(value="/memberInsert.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String memberInsert(MemberDTO dto, HttpServletRequest req) {

try {

dao.insertData("mySql.addMember", dto);

} catch (Exception e) {

System.out.println(e.toString());

}

//sendRedirect() 메소드 역할

return "redirect:memberList.mvc";

}

}






//ScoreController.java -> 컨트롤러클래스. 데이터베이스 액세스 전용 클래스

package com.test;


import java.util.List;


import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


import com.spring.dao.CommonDAO;


@Controller("scoreController")

public class ScoreController {


//iBatis 연결 객체인 IBatisDaoImpl 클래스를 dao 변수와 연결시킨다.

@Resource(name="dao")

private CommonDAO dao;

@RequestMapping(value="/scoreList.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String scoreList(ScoreDTO dto, HttpServletRequest req) {

try {

List<Object> arrayList = dao.getListData("mySql.listsScore");

req.setAttribute("arrayList", arrayList);

} catch (Exception e) {

System.out.println(e.toString());

}

return "scoreList.jsp";

}

@RequestMapping(value="/scoreInsertForm.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String scoreInsertForm(ScoreDTO dto, HttpServletRequest req) {

try {

Object newdto = dao.getReadData("mySql.searchMember", dto.getMid());

req.setAttribute("dto", newdto);

} catch (Exception e) {

System.out.println(e.toString());

}

//forward() 메소드 역할

return "scoreInsertForm.jsp";

}

@RequestMapping(value="/scoreInsert.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String scoreInsert(ScoreDTO dto) {


try {

dao.insertData("mySql.addScore", dto);

} catch (Exception e) {

System.out.println(e.toString());

}

//sendRedirect() 메소드 역할

return "redirect:scoreList.mvc";

}

}






//BasicStyle.css

@CHARSET "EUC-KR";

body {

color:#2f3743;

font-size:10pt;

}

a {

text-decoration:none;

color:gray;

}


a:hover {

text-decoration:underline;

color:red;

}


table.style00 td, table.style00 th 

{

padding: 3px;

border-right-style: solid;

border-bottom-style: solid;

border-width: 1px;

border-color: #6980b8;

}


table.style00 td:hover 

{

background-color:#d2d2d2;

}


#result {

overflow:auto;  /* DIV 태그 내부에 스크롤 생성 */ 

height:100px;

}




//memberList.jsp -> JSTL, EL 표현으로 대체

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">

<style type="text/css">

.style1 {

text-align: center;

}

</style>


<script type="text/javascript">

function deleteForm(mid) {

if (confirm("선택한 자료를 삭제할까요?")) {

window.location.href="memberDelete.mvc?mid="+mid;

}

}

</script>


</head>

<body onload="msg()">

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<p>[<a href="memberInsertForm.mvc">회원등록</a>]</p>

<table style="width:400px;" class="style00">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th><th></th><th></th></tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="style1">${dto.mid}</td>

<td class="style1">${dto.name}</td>

<td class="style1">${dto.tel}</td>

<td class="style1"><a href="memberUpdateForm.mvc?mid=${dto.mid}">[수정]</a></td>

<td class="style1">

<!-- 성적이 등록된 경우는 삭제가 안되도록 함 -->

<c:choose>

<c:when test="${dto.count > 0}">[삭제]</c:when>

<c:otherwise><a href="javascript:deleteForm(${dto.mid})">[삭제]</a></c:otherwise>

</c:choose>

</td>

</tr>

</c:forEach>

</tbody>

</table>

</div>

</div>

</body>

</html>




//memberInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈 칸 검사

if (name.value == ""

|| tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<h3>-회원 등록-</h3>

<form action="memberInsert.mvc" method="post" id="myForm">

<table>

<tbody>

<tr>

<td>이름</td>

<td><input type="text" name="name" id="name"></td>

</tr>

<tr>

<td>전화</td>

<td><input type="text" name="tel" id="tel"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">등록</a>]

[<a href="memberList.mvc">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>




//memberUpdateForm.jsp -> JSTL, EL 표현으로 대체

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈 칸 검사

if (name.value == ""

|| tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<h3>-회원 수정-</h3>

<form action="memberUpdate.mvc" method="post" id="myForm">


<%-- 회원 수정을 위해서 반드시 전송해야 되는 값 --%>

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

<table>

<tbody>

<tr>

<td>이름</td>

<td><input type="text" name="name" id="name" value="${dto.name}"></td>

</tr>

<tr>

<td>전화</td>

<td><input type="text" name="tel" id="tel" value="${dto.tel}"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">수정</a>]

[<a href="memberList.mvc">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>




//scoreList.jsp -> JSTL, EL 표현으로 대체

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">

<style type="text/css">

.style1 {

text-align: center;

}

.style2 {

text-align: right;

}

</style>


<script type="text/javascript">

function deleteForm(mid) {

if (confirm("선택한 자료를 삭제할까요?")) {

window.location.href="scoreDelete.mvc?mid="+mid;

}

}

</script>


</head>

<body>

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<table style="width:600px;" class="style00">

<tbody>

<tr><th>번호</th><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th><th>판정</th><th></th></tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="style1">${dto.mid}</td>

<td class="style1">${dto.name}</td>

<td class="style2">

<c:choose>

<c:when test="${empty dto.kor}">X</c:when>

<c:otherwise>${dto.kor}</c:otherwise>

</c:choose>

</td>

<td class="style2">

<c:choose>

<c:when test="${empty dto.eng}">X</c:when>

<c:otherwise>${dto.eng}</c:otherwise>

</c:choose>

</td>

<td class="style2">

<c:choose>

<c:when test="${empty dto.mat}">X</c:when>

<c:otherwise>${dto.mat}</c:otherwise>

</c:choose>

</td>

<td class="style2">

<c:choose>

<c:when test="${empty dto.tot}">X</c:when>

<c:otherwise>${dto.tot}</c:otherwise>

</c:choose>

</td>

<td class="style2">

<c:choose>

<c:when test="${empty dto.ave}">X</c:when>

<c:otherwise><fmt:formatNumber value="${dto.ave}" pattern="0.0"></fmt:formatNumber></c:otherwise>

</c:choose>

</td>

<td class="style1">${dto.grade}</td>

<td class="style1">

<c:choose>

<c:when test="${empty dto.kor}">

<a href="scoreInsertForm.mvc?mid=${dto.mid}">[입력]</a> [수정] [삭제]

</c:when>

<c:otherwise>

[입력] <a href="scoreUpdateForm.mvc?mid=${dto.mid}">[수정]</a> <a href="javascript:deleteForm(${dto.mid})">[삭제]</a>

</c:otherwise>

</c:choose>

</td>

</tr>

</c:forEach>

</tbody>

</table>

</div>

</div>

</body>

</html>




//scoreInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(kor.value == "" || eng.value ==""|| mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}


//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<h3>-성적 입력-</h3>

<form action="scoreInsert.mvc" method="post" id="myForm">

<%-- 성적 입력을 위해서 반드시 전송해야 되는 값 --%>

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

<table>

<tbody>

<tr>

<td>이름</td>

<td><span style="font-weight: bold;">${dto.name}</span></td>

</tr>

<tr>

<td>국어</td>

<td><input type="text" name="kor" id="kor"></td>

</tr>

<tr>

<td>영어</td>

<td><input type="text" name="eng" id="eng"></td>

</tr>

<tr>

<td>수학</td>

<td><input type="text" name="mat" id="mat"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">등록</a>]

[<a href="scoreList.mvc">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">국어, 영어, 수학 점수를 0~100 사이의 숫자로 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>




//scoreUpdateForm.jsp -> JSTL, EL 표현으로 대체

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(kor.value == "" || eng.value ==""|| mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}


//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="memberList.mvc">회원관리</a>]

[<a href="scoreList.mvc">성적관리</a>]

<hr>

</div>

<div>

<h3>-성적 수정-</h3>

<form action="scoreUpdate.mvc" method="post" id="myForm">

<%-- 성적 수정을 위해서 반드시 전송해야 되는 값 --%>

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

<table>

<tbody>

<tr>

<td>이름</td>

<td><span style="font-weight: bold;">${mdto.name}</span></td>

</tr>

<tr>

<td>국어</td>

<td><input type="text" name="kor" id="kor" value="${sdto.kor}"></td>

</tr>

<tr>

<td>영어</td>

<td><input type="text" name="eng" id="eng" value="${sdto.eng}"></td>

</tr>

<tr>

<td>수학</td>

<td><input type="text" name="mat" id="mat" value="${sdto.mat}"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">수정</a>]

[<a href="scoreList.mvc">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">국어, 영어, 수학 점수를 0~100 사이의 숫자로 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>





//요청주소

http://localhost:8090/MemberScore_Spring_20121227/memberList.mvc


---------------------------------------------------

문제) 성적 수정, 삭제와 회원 수정, 삭제 과정은 각자 작성할 것.







------------------------------------------------------

문제) 직원관리 Spring, iBatis 버전 작성. 팀별 작업.

-> 새 프로젝트 생성(EmployeeSpring_20121227)

-> 메뉴 구성 추가

-> emp.sql 쿼리를 먼저 실행해서 환경 구성할 것.


--------------------------------------

--지역 검색 쿼리

SELECT city_id, city FROM city ORDER BY city_id


--부서 검색 쿼리

SELECT buseo_id, buseo FROM buseo ORDER BY buseo_id


--직위 검색 쿼리

SELECT jikwi_id, jikwi FROM jikwi ORDER BY jikwi_id


--직위별 최소 기본급 검색 쿼리

SELECT min_basicpay FROM jikwi WHERE jikwi_id=9


--입력 쿼리

INSERT INTO emp (emp_id, name, ssn, ibsadate, city_id, tel, buseo_id, jikwi_id, basicpay, sudang) 

VALUES (empSeq.nextval

, '홍길동'

, '771212-1022432'

, '1998-10-11'

, 6

, '011-2356-4528'

, 7

, 9

, 2610000

, 200000)


--직원 명단 출력 쿼리(emp 테이블이 아니라 empView 이용)

SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate

, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay

, sudang, pay 

FROM empView 

ORDER BY emp_id ASC


--전체 직원수 출력 쿼리 (emp 테이블이나 empView나 결과 동일함)

SELECT COUNT(*) AS count 

FROM emp


--검색 쿼리(emp 테이블이 아니라 empView 이용)

SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate

, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay

, sudang, pay 

FROM empView 

WHERE emp_id = 1001

ORDER BY emp_id ASC


--수정 쿼리

UPDATE emp

SET name='새로운 이름'

, ssn='새로운 주민번호'

, ibsadate='새로운 입사일'

, city_id=1

, tel='새로운 전화번호'

, buseo_id=1

, jikwi_id=1

, basicpay=1

, sudang=1

WHERE emp_id=1001


--삭제 쿼리

DELETE emp

WHERE emp_id=1001



--직원용 ID(이름), PW(주민번호 뒷자리) 검사 쿼리

SELECT COUNT(*) AS count 

FROM emp

WHERE name='이순신' AND SUBSTR(ssn, 8, 7)='1544236';


--직원 전용 employeeView

CREATE OR REPLACE VIEW employeeView

AS

SELECT emp_id, name, ibsadate, c.city_id AS city_id, city, tel, b.buseo_id AS buseo_id, buseo, j.jikwi_id AS jikwi_id, jikwi 

FROM emp e, city c, buseo b, jikwi j

WHERE e.city_id=c.city_id AND e.buseo_id=b.buseo_id AND e.jikwi_id=j.jikwi_id

ORDER BY emp_id ASC;



--------------------------------------

--관리자 전용 테이블


CREATE TABLE empAdmin (

id VARCHAR2(20) --PK

,pw VARCHAR2(20) --암호화. encrypt() 사용자 정의 함수 이용.

);


ALTER TABLE empAdmin

ADD CONSTRAINT empAdmin_id_pk PRIMARY KEY(id);


INSERT INTO empAdmin (id, pw) VALUES ('admin', encrypt('1234', 'admin'));

INSERT INTO empAdmin (id, pw) VALUES ('hong', encrypt('1234', 'hong'));

COMMIT;


SELECT id, pw FROM empAdmin;


--관리자용 ID, PW 검사 쿼리

SELECT COUNT(*) AS count FROM empAdmin

WHERE id='admin' AND pw=encrypt('1234', 'admin');



--------------------------------------


//EmployeeDTO.java


//CityDTO.java


//BuseoDTO.java


//JikwiDTO.java


//EmployeeIbatis.xml


//CityIbatis.xml


//BuseoIbatis.xml


//JikwiIbatis.xml


//sqlMapConfig.xml


//CityController.java -> 지역관리용 컨트롤러 클래스.


//City.jsp


//BuseoController.java -> 부서관리용 컨트롤러 클래스


//Buseo.jsp


//JikwiController.java -> 직위관리용 컨트롤러 클래스


//Jikwi.jsp


//BasicStyle.css


//EmployeeController.java -> 직원관리용 컨트롤러 클래스


//Employee_Select.jsp -> JSTL, EL 표기 사용


//Employee_Search.jsp


//Employee_InsertForm.jsp


//Employee_UpdateForm.jsp


//Employee_DeleteForm.jsp


//LoginForm.jsp


//MainMenu.jsp -> 메인 메뉴 전용.


//요청주소

http://localhost:8090/EmployeeSpring_20121227/loginForm.mvc


-------------------------------------------------




'Java > Spring, iBatis' 카테고리의 다른 글

[20121228] 8일차 (SpringMVC Annotation, iBatis)  (0) 2012.12.28
[20121226] 6일차(Spring, iBatis)  (0) 2012.12.28

WRITTEN BY
빨강꼬마

,

-------------------------------------------------

Spring 환경 설정


1. 다이나믹 웹 프로젝트 생성 후

2. SpringMVC_iBatis 환경 설정(JAR 파일 포함) 폴더에 있는 내용을 덮어쓰기할 것.



-------------------------------------------------

Controller 테스트1(AbstractController)



//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>spring</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  

  <!-- 한글 인코딩 설정을 euc-kr로 수정할 것 -->

    <filter>

        <filter-name>CharacterEncoding</filter-name>

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

        <init-param>

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

            <param-value>euc-kr</param-value>

        </init-param>

    </filter>


    <filter-mapping>

        <filter-name>CharacterEncoding</filter-name>

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

    </filter-mapping>

  

   <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    </servlet>

    

    <!-- 서블릿 요청 주소에서 확장자를 *.mvc로 수정할 것 -->

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

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

    </servlet-mapping>


<listener>

  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

</web-app>





//dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix" value="/" /> 

    <property name="suffix" value=".jsp" /> 

</bean>


<!-- 사용자 요청 서블릿 주소 등록 -->

<bean id="beanNameUrlMapping"

class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

<bean name="/msg.mvc" class="com.test.Controller01"></bean>


 </beans>  





//Controller01.java

package com.test;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;


public class Controller01 extends AbstractController {


//매개변수 이름을 req, resp로 수정해서 사용할 것

@Override

protected ModelAndView handleRequestInternal(HttpServletRequest req,

HttpServletResponse resp) throws Exception {

String msg = "Hello, Spring World!";

req.setAttribute("msg", msg);

//뷰 역할을 하는 JSP 페이지 지정할 것.

//확장자 생략

return new ModelAndView("receive01");

}


}





//receive01.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h1>Controller 테스트1(AbstractController)</h1>

<div>${msg}</div>

</div>

</body>

</html>





//요청주소

http://localhost:8090/SpringTest/msg.mvc



-------------------------------------------------

Spring Annotation 환경 설정


1. 다이나믹 웹 프로젝트 생성 후

2. SpringMVC_Annotation_iBatis 연동 환경 설정(JAR 파일 포함) 폴더에 있는 내용을 덮어쓰기할 것.



--------------------------------------------------

SpringMVC Annotation 테스트


//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>spring</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 한글 인코딩 설정을 euc-kr로 수정할 것 -->

    <filter>

        <filter-name>CharacterEncoding</filter-name>

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

        <init-param>

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

            <param-value>euc-kr</param-value>

        </init-param>

    </filter>


    <filter-mapping>

        <filter-name>CharacterEncoding</filter-name>

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

    </filter-mapping>

  

   <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 

        <init-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/dispatcher-servlet.xml,

/WEB-INF/applicationContext.xml

</param-value>

        </init-param>

        --> 

    </servlet>

    

    <!-- 서블릿 요청 주소에서 확장자를 *.mvc로 수정할 것 -->

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

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

    </servlet-mapping>


<listener>

  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

</web-app>





//Controller02.java

package com.test;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;



//@Controller 어노테이션은 현재 클래스를 컨트롤러로 지정하게 됨

//@RequestMapping 어노테이션은 사용자 요청 서블릿 주소 등록함

@Controller

@RequestMapping(value="/msg.mvc")

public class Controller02 {

//사용자 정의 메소드 구성

//메소드 위에 어노테이션을 추가함으로서 자동 호출됨

//메소드 안에 매개변수 지정은 임의로 추가 지정 가능

@RequestMapping(method=RequestMethod.GET)

public String method(HttpServletRequest req,

HttpServletResponse resp) {


String msg = "Hello, Spring World!";

req.setAttribute("msg", msg);

//뷰 역할을 할 JSP 페이지 주소 지정할 것.

return "receive02.jsp";

}

}





//receive02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h1>SpringMVC Annotation 테스트</h1>

<div>${msg}</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/SpringAnnotationTest/msg.mvc




----------------------------------------------------

SpringMVC Annotation에서 데이터 전송 테스트


//send03.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

//이름, 전화번호가 비어있는지 검사하는 과정 추가

//이름, 전화번호가 채워진 경우만 데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>데이터 송수신 테스트1</h2>

<!-- <form> 태그에서 action, method 속성 필수 -->

<form action="receive03.mvc" method="post">

<!-- JSP에서는 식별자를 name 속성으로 구분 -->

이름 <input type="text" name="name"><br>

전화 <input type="text" name="tel"><br>

<!-- submit 버튼을 클릭하면 데이터 전송됨 -->

<!-- <input type="submit" value="회원가입"><br> -->

<!-- 자바스크립트 연동시 submit 대신 button 으로 처리 -->

<input type="button" value="회원가입"

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화번호를 채워야 합니다.</span>

</form>

</div>

</body>

</html>




//receive03.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트1</h2>

<!-- 데이터 전송시 사용했던 식별자와 EL 표현의 식별자는 동일해야 한다. --> 

<h3>name:${name}, tel:${tel}</h3>

</div>

</body>

</html>





//UserDTO.java

package com.test;


//SpringMVC Annotation에서 사용하는 데이터 저장소 객체

public class UserDTO {

//사용자가 사용하는 식별자와 멤버변수는 동일한 명칭 사용할 것.

private String name, tel;


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getTel() {

return tel;

}


public void setTel(String tel) {

this.tel = tel;

}


}





//Controller03.java

package com.test;


import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


//@Controller("컨트롤러ID")

@Controller("controller03")

public class Controller03 {


//@RequestMapping 어노테이션은 사용자 요청 서블릿 주소 등록함

//메소드 단위로 @RequestMapping 어노테이션 지정 가능

//method 인자는 요청 방식 지정하는 부분

@RequestMapping(value="/send03.mvc", method=RequestMethod.GET)

public String send03() {

//뷰 역할을 할 JSP 페이지 주소 지정할 것.

return "send03.jsp";

}

//method 인자는 요청 방식 지정하는 부분

//데이터 전송 전용 객체(UserDTO) 지정은 메소드 인자로 설정한다.

//메소드 안에 매개변수 지정은 임의로 추가 지정 가능

@RequestMapping(value="/receive03.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String receive03(UserDTO dto, HttpServletRequest req) {

//데이터 수신 확인

System.out.println(dto.getName());

System.out.println(dto.getTel());

req.setAttribute("name", dto.getName());

req.setAttribute("tel", dto.getTel());

//뷰 역할을 할 JSP 페이지 주소 지정할 것.

return "receive03.jsp";

}

}





//요청주소

http://localhost:8090/SpringAnnotationTest/send03.mvc




-----------------------------------------

이름과 전화번호를 저장하는 JDBC 프로그램 작성. 

오라클, SpringMVC Annotation, iBatis, JSP 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------



--------------------------------

//회원 테이블 생성. 회원번호, 이름, 전화번호. 시퀀스 객체 생성.

CREATE TABLE member (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member

ADD CONSTRAINT member_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE memberSeq;



//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, 'hong', '111-1111')


-----------------------------------------

//applicationContext.xml -> 데이터베이스 연결 계정 등록

<?xml version="1.0" encoding="UTF-8"?>  

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">



<!-- 데이터베이스 연결 계정 등록할 것 --> 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>

<property name="username" value="scott"/>

<property name="password" value="tiger"/>

</bean>

<!-- Transaction Manager for a single JDBC DataSource -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>


<bean id="sqlMapClient"

           class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"

           p:dataSource-ref="dataSource"

           p:configLocation="WEB-INF/sqlMapConfig/sqlMapConfig.xml"/>

<bean id="sqlMapClientTemplate"

           class="org.springframework.orm.ibatis.SqlMapClientTemplate"

           p:sqlMapClient-ref="sqlMapClient" />

           

</beans>  




//mySqlMap.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">


<!-- sqlMap 엘리먼트에서 namespace의 값을 유일하게 지정할 것 -->    

<sqlMap namespace="mySql">

<!-- id 속성은 쿼리 객체 접근시 식별자로 사용된다. -->

<!-- resultClass 속성은 쿼리 실행 결과를 저장하는 저장소 객체 -->

<!-- SELECT 쿼리의 컬럼 리스트는 MemberDTO의 변수명과 일치해야 한다. -->

<select id="lists" resultClass="com.test.MemberDTO">

SELECT mid, name, tel FROM member ORDER BY mid

</select>

<!-- parameterClass 속성은 외부 데이터를 쿼리에 전달하는 저장소 객체 -->

<!-- #변수명#은 MemberDTO의 변수명과 일치해야 한다. -->

<insert id="add" parameterClass="com.test.MemberDTO">

INSERT INTO member (mid, name, tel) 

VALUES (memberSeq.nextval, #name#, #tel#)

</insert>


</sqlMap>





//sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMapConfig      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">


<sqlMapConfig>


  <settings

    cacheModelsEnabled="false"

    useStatementNamespaces="true"/>


  <!-- iBatis XML 파일 등록 -->

  <sqlMap resource="com/spring/dao/sqlMap/mySqlMap.xml"/>

  

  

</sqlMapConfig>




//MemberDTO.java

package com.test;


public class MemberDTO {


private int mid;

private String name, tel;

public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}

}





//member.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>회원 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">

<style type="text/css">

.style1 {

text-align: center;

}

</style>


<script type="text/javascript">

function myFunc() {

var obj = document.getElementById("myForm");

//데이터 검사 과정 추가

//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

<h3>-회원 등록-</h3>

<form method="post" id="myForm">

<table>

<tbody>

<tr>

<td>이름</td>

<td><input type="text" name="name" id="name"></td>

</tr>

<tr>

<td>전화</td>

<td><input type="text" name="tel" id="tel"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">등록</a>]

<span id="msg" style="font-size:10pt; color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>


<div>


<table style="width:400px;" class="style00">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="style1">${dto.mid}</td>

<td class="style1">${dto.name}</td>

<td class="style1">${dto.tel}</td>

</tr>

</c:forEach>

</tbody>

</table>

</div>

</div>

</body>

</html>





//BasicStyle.css

@CHARSET "EUC-KR";

body {

color:#2f3743;

font-size:10pt;

}

a {

text-decoration:none;

color:gray;

}


a:hover {

text-decoration:underline;

color:red;

}


table.style00 td, table.style00 th 

{

padding: 3px;

border-right-style: solid;

border-bottom-style: solid;

border-width: 1px;

border-color: #6980b8;

}


table.style00 td:hover 

{

background-color:#d2d2d2;

}


#result {

overflow:auto;  /* DIV 태그 내부에 스크롤 생성 */ 

height:100px;

}



//MemberController.java

package com.test;


import java.util.ArrayList;

import java.util.List;


import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


import com.spring.dao.CommonDAO;


//@Controller("컨트롤러ID")

@Controller("memberController")

public class MemberController {


//iBatis 연결 객체인 IBatisDaoImpl 클래스를 dao 변수와 연결시킨다.

@Resource(name="dao")

private CommonDAO dao;

//@RequestMapping 어노테이션은 사용자 요청 서블릿 주소 등록함

//데이터 전송 전용 객체(UserDTO) 지정은 메소드 인자로 설정한다.

//메소드 안에 매개변수 지정은 임의로 추가 지정 가능

@RequestMapping(value="/member.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String member(MemberDTO dto, HttpServletRequest req) {

//INSERT 쿼리 실행 액션 수행

if (dto.getName() != null

&& !dto.getName().equals("")) {

try {

dao.insertData("mySql.add", dto);

} catch (Exception e) {

System.out.println(e.toString());

}

}

//SELECT 쿼리 실행 부분

List<Object> arrayList = new ArrayList<Object>();

try {

arrayList = dao.getListData("mySql.lists");

} catch (Exception e) {

System.out.println(e.toString());

}

req.setAttribute("arrayList", arrayList);

//뷰 역할을 할 JSP 페이지 주소 지정할 것.

return "member.jsp";

}

}




//IBatisDaoImpl.java

package com.spring.dao;


import java.util.List;

import java.util.Map;


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

import org.springframework.orm.ibatis.SqlMapClientTemplate;

import org.springframework.stereotype.Repository;


@Repository("dao")

public class IBatisDaoImpl implements CommonDAO {

/*

 @Repository : 저장소 컴포넌트(DAO 등).

 @Service : 상태없는 서비스 컴포넌트.

 @Autowired 어노테이션 : Spring에서 의존관계를 자동으로 설정

 @Resource 어노테이션 : 의존하는 빈 객체를 전달 할 때 사용


 @Resource 는 이름을 지정할 수 있으나 @Autowired는 이름을 지정할 수 없고 id 값과 일치해야한다.


      - Service에 있는 @Autowired는 @Repository("dao")에 등로된 dao와 변수명이 같아야 한다.

 - @Autowired 어노테이션은 Spring에서 의존관계를 자동으로 설정

*/


@Autowired

private SqlMapClientTemplate sqlMapClientTemplate;

public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) {

this.sqlMapClientTemplate = sqlMapClientTemplate;

}


// ******************************************************************

// 데이터 추가

    public void insertData(String id, Object value) throws Exception {

try {

// sqlMapClientTemplate.getSqlMapClient().startTransaction();

// sqlMapClientTemplate.getSqlMapClient().getCurrentConnection().setAutoCommit( false );

sqlMapClientTemplate.insert(id, value);  // return Object

// sqlMapClientTemplate.getSqlMapClient().getCurrentConnection().commit();

} catch (Exception e) {

System.out.println(e.toString());

throw e;

} finally {

// sqlMapClientTemplate.getSqlMapClient().getCurrentConnection().setAutoCommit( true );

// sqlMapClientTemplate.getSqlMapClient().endTransaction();

}    

    }

    

// ******************************************************************

// 데이터 수정

    public int updateData(String id, Object value) throws Exception {

int result = 0;

try {

     result = sqlMapClientTemplate.update(id, value);

} catch (Exception e) {

System.out.println(e.toString());

throw e;

}

return result;

    }

    public int updateData(String id, Map<String, Object> map) throws Exception {

int result = 0;

try {

     result = sqlMapClientTemplate.update(id, map);

} catch (Exception e) {

System.out.println(e.toString());

throw e;

}

return result;

    }

    

// ******************************************************************

// 데이터 삭제

public int deleteData(String id, Map<String, Object> map) throws Exception {

int result = 0;


try {

result = sqlMapClientTemplate.delete(id, map);

} catch (Exception e) {

System.out.println(e.toString());

throw e;

}


return result;

    }

public int deleteData(String id, Object value) throws Exception {

int result = 0;

try {

result = sqlMapClientTemplate.delete(id, value);

} catch (Exception e) {

System.out.println(e.toString());

throw e;

}


return result;

    }

public int deleteAll(String id) throws Exception {

int result = 0;

try {

    result = sqlMapClientTemplate.delete(id);

} catch (Exception e) {

System.out.println(e.toString());

throw e;

}


return result;

    }


// ******************************************************************

// 레 코드 수 / 최대 값 구하기

public int getIntValue(String id, Map<String, Object> map) throws Exception {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id, map)).intValue();

return num;

    }

public int getIntValue(String id, Object value) throws Exception {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id, value)).intValue();

return num;

    }

public int getIntValue(String id) throws Exception {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id)).intValue();

return num;

    }

// ******************************************************************

// 테이블의 레코드를 리스트에 저장

@SuppressWarnings("unchecked")

public List<Object> getListData(String id, Map<String, Object> map) throws Exception {

List<Object> lists = (List<Object>) sqlMapClientTemplate.queryForList(id, map);

return lists;

}

@SuppressWarnings("unchecked")

public List<Object> getListData(String id, Object value) throws Exception {

List<Object> lists = (List<Object>) sqlMapClientTemplate.queryForList(id, value);

return lists;

}

@SuppressWarnings("unchecked")

public List<Object> getListData(String id) throws Exception {

List<Object> lists = (List<Object>) sqlMapClientTemplate.queryForList(id);

return lists;

}

// ******************************************************************

// 해당 레코드 가져오기

public Object getReadData(String id) throws Exception {

return  sqlMapClientTemplate.queryForObject(id);

}

public Object getReadData(String id, Object value) throws Exception {

return  sqlMapClientTemplate.queryForObject(id, value);

}

public Object getReadData(String id, Map<String, Object> map) throws Exception {

return  sqlMapClientTemplate.queryForObject(id, map);

}

}







//요청주소

http://localhost:8090/SpringAnnotationTest/member.mvc







------------------------------------------

문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 

오라클, SpringMVC Annotation, iBatis 이용. 

총점 기준 정렬(내림차순) 출력.



판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 ----------------

이름 [kim   ]

국어 [80    ]

영어 [90    ]

수학 [80    ]

[ 등록 ]


---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------



---------------------------------------------

--오라클에 성적 저장용 테이블 생성

CREATE TABLE score (

sid NUMBER --PK, 자동 번호 부여

,name VARCHAR2(10)

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score

ADD CONSTRAINT score_sid_pk PRIMARY KEY (sid);

ALTER TABLE score

ADD CONSTRAINT score_kor_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_mat_ck CHECK (mat BETWEEN 0 AND 100);


--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE scoreSeq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score (sid, name, kor, eng, mat)

VALUES (scoreSeq.nextval, 'hong', 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave


--, 조건검사 쿼리 추가 ->합격, 불합격, 과락 출력

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade


FROM score

ORDER BY tot DESC


--scoreView 생성

CREATE OR REPLACE VIEW scoreView

AS

SELECT sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave


--, 조건검사 쿼리 추가 ->합격, 불합격, 과락 출력

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade


FROM score

ORDER BY tot DESC;



--scoreView를 이용한 SELECT 쿼리

SELECT sid, name, kor, eng, mat, tot, ave, grade 

FROM scoreView 

ORDER BY tot DESC



------------------------------------------

//ScoreDTO.java

package com.test;


public class ScoreDTO {


private String name;

private int kor, eng, mat;


private int tot;

private double ave;

private String grade;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKor() {

return kor;

}

public void setKor(int kor) {

this.kor = kor;

}

public int getEng() {

return eng;

}

public void setEng(int eng) {

this.eng = eng;

}

public int getMat() {

return mat;

}

public void setMat(int mat) {

this.mat = mat;

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public double getAve() {

return ave;

}

public void setAve(double ave) {

this.ave = ave;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}

}






//scoreIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">


<!-- sqlMap 엘리먼트에서 namespace의 값을 유일하게 지정할 것 -->    

<sqlMap namespace="score">

<!-- id 속성은 쿼리 객체 접근시 식별자로 사용된다. -->

<!-- resultClass 속성은 쿼리 실행 결과를 저장하는 저장소 객체 -->

<!-- SELECT 쿼리의 컬럼 리스트는 ScoreDTO의 변수명과 일치해야 한다. -->

<select id="lists" resultClass="com.test.ScoreDTO">

SELECT sid, name, kor, eng, mat, tot, ave, grade 

FROM scoreView 

ORDER BY tot DESC

</select>

<!-- parameterClass 속성은 외부 데이터를 쿼리에 전달하는 저장소 객체 -->

<!-- #변수명#은 ScoreDTO의 변수명과 일치해야 한다. -->

<insert id="add" parameterClass="com.test.ScoreDTO">

INSERT INTO score (sid, name, kor, eng, mat)

VALUES (scoreSeq.nextval, #name#, #kor#, #eng#, #mat#)

</insert>


</sqlMap>






//sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMapConfig      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">


<sqlMapConfig>


  <settings

    cacheModelsEnabled="false"

    useStatementNamespaces="true"/>


  <!-- iBatis XML 파일 등록 -->

  <sqlMap resource="com/spring/dao/sqlMap/mySqlMap.xml"/>

  <sqlMap resource="com/spring/dao/sqlMap/scoreIbatis.xml"/>

  

  

</sqlMapConfig>





//score.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>


<style type="text/css">

.subject {

width:80px;

}

.style1 {

text-align: center;

}

.style2 {

text-align: right;

}

</style>


<script type="text/javascript">

function myFunc(obj){

var name = document.getElementById('name');

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(name.value == "" || kor.value == "" || eng.value =="" || mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/) ||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>성적 처리(SpringMVC Annotation, iBatis)</h2>

<form method="post">

이름 <input type="text" name="name" id="name"><br> 

국어 <input type="text" name="kor" id="kor" class="subject"><br>

영어 <input type="text" name="eng" id="eng" class="subject"><br>

수학 <input type="text" name="mat" id="mat" class="subject"><br>

<input type="button" value=" 등록 "

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 국어, 영어, 수학을 입력해야 합니다.<br>국어, 영어, 수학을 0~100 사이의 숫자를 입력해야 합니다.</span>

</form>

<h3>출력 ------------</h3>

<div>

<table border="1" style="width:500px;">

<tbody>

<tr>

<th>등수</th>

<th>이름</th>

<th>국어</th>

<th>영어</th>

<th>수학</th>

<th>총점</th>

<th>평균</th>

<th>판정</th>

</tr>

<c:set var="sid" value="0"></c:set>

<c:forEach var="dto" items="${arrayList}">

<c:set var="sid" value="${sid+1}"></c:set>

<tr>

<td class="style1">${sid}</td>

<td class="style1">${dto.name}</td>

<td class="style2">${dto.kor}</td>

<td class="style2">${dto.eng}</td>

<td class="style2">${dto.mat}</td>

<td class="style2">${dto.tot}</td>

<td class="style2"><fmt:formatNumber value="${dto.ave}" pattern="0.0"></fmt:formatNumber></td>

<td class="style1">${dto.grade}</td>

</tr>

</c:forEach>

</tbody>

</table>

</div>

</div>

</body>

</html>





//ScoreController.java

package com.test;


import java.util.ArrayList;

import java.util.List;


import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


import com.spring.dao.CommonDAO;


@Controller("scoreController")

public class ScoreController {

//iBatis 연결 객체인 IBatisDaoImpl 클래스를 dao 변수와 연결시킨다.

@Resource(name="dao")

private CommonDAO dao;

//@RequestMapping 어노테이션은 사용자 요청 서블릿 주소 등록함

//데이터 전송 전용 객체(UserDTO) 지정은 메소드 인자로 설정한다.

//메소드 안에 매개변수 지정은 임의로 추가 지정 가능

@RequestMapping(value="/score.mvc", method={RequestMethod.GET, RequestMethod.POST})

public String score(ScoreDTO dto, HttpServletRequest req) {

//INSERT 쿼리 실행 액션 수행

if (dto.getName() != null

&& !dto.getName().equals("")) {

try {

dao.insertData("score.add", dto);

} catch (Exception e) {

System.out.println(e.toString());

}

}

//SELECT 쿼리 실행 부분

List<Object> arrayList = new ArrayList<Object>();

try {

arrayList = dao.getListData("score.lists");

} catch (Exception e) {

System.out.println(e.toString());

}

req.setAttribute("arrayList", arrayList);

return "score.jsp";

}

}





//요청주소

http://localhost:8090/SpringAnnotationTest/score.mvc



------------------------------------------------






WRITTEN BY
빨강꼬마

,

----------------------------------

상담게시판 회원 가입 (아이디 중복 체크)


//memberInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function msg() {


}

</script>


</head>

<body onload="msg()">

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[회원가입]</h3>

<form action="memberInsert.action" method="post" id="memberForm">

* 등록된 전화로 통화가 가능한 경우에만 회원 가입이 완료됩니다.<br>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="200px">*아이디<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="id" name="id"><a href="javascript:idCheck()">[아이디 중복확인]</a><span id="idMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*이름<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="name" name="name"><span id="nameMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*이메일<span style="font-size:9pt;">(100자 이내)</span></td>

<td class="bTitle"><input type="text" id="email" name="email" style="width:300px"><span id="emailMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*전화<span style="font-size:9pt;">(30자 이내)</span></td>

<td class="bTitle"><input type="text" id="tel" name="tel" style="width:300px"><span id="telMsg"></span></td>

</tr>

</table>

<br>

<a href="javascript:memberFormSubmit()">[확인]</a>

<span id="submitMsg"></span>

</form>

</div>

</div>


</body>

</html>






//memberStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="member" extends="struts-default" namespace="" >        

<action name="login" 

class="com.test.MemberAction" 

method="login">

<result name="error">/login.jsp</result>

<result name="success">/memberInfo.jsp</result>

</action>

<action name="logout"

class="com.test.MemberAction"

method="logout">

<result type="redirectAction">login.action</result>

</action>

<action name="memberInfo"

class="com.test.MemberAction" 

method="memberInfo">

<result>/memberInfo.jsp</result>

</action>

<action name="memberInsertForm">

<result>/memberInsertForm.jsp</result>

</action>

<action name="memberIDCheck"

class="com.test.MemberAction" 

method="memberIDCheck">

<result>/memberIDCheck.jsp</result>

</action>

</package>

</struts>





//consultation.js -> Ajax 요청 주소만 변경함

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.action?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

obj.submit();

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.action";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------




function memberPwFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberPwForm");


var pw = document.getElementById("pw");

var newpw = document.getElementById("newpw");

var pwMsg = document.getElementById("pwMsg");

var newpwMsg = document.getElementById("newpwMsg");

pwMsg.style.display = "none";

newpwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (newpw.value == "" || newpw.value.length > 20) {

newpwMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}



function memberModifyFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberModifyForm");


var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}






//MemberAction.java

package com.test;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

public String memberIDCheck() {

HttpServletRequest req = ServletActionContext.getRequest();

String data = req.getParameter("data");

String result = "OK";

CommonDAO dao = CommonDAOImpl.getInstance();


dto.setId(data);

int returnValue = dao.getIntValue("member.duplicateID", dto);

if (returnValue == 1) {

result = "Cancel";

}

req.setAttribute("result", result);

return SUCCESS;

}

}





//memberIDCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String result = (String)request.getAttribute("result");

out.write(result);

%>




--------------------------------------------------

문제) 회원 가입의 나머지 절차는 각자 작성할 것.


//memberStruts.xml -> memberInsert.action 주소 등록

//memberIbatis.xml -> INSERT 쿼리 등록

//MemberAction.java -> memberInsert() 메소드 등록

//memberInsertOK.jsp -> 회원 가입 완료 메시지 페이지 작성




---------------------------------------------------

상담 게시판 회원 명단 (관리자, 직원 전용)



//memberInfo.jsp -> 관리자 전용 [*회원명단] 메뉴 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>        

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function msg() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle">${dto.id}</td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle">${dto.name}</td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle">${dto.email}</td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle">${dto.tel}</td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle">${array[dto.grade-1]}</td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자, 직원 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1' || sessionScope.grade == '2'}">

<a href="memberList.action">[*회원명단]</a>

</c:if>


<a href="memberPWModifyForm.action">[패스워드변경]</a>

<a href="memberModifyForm.action">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>




//memberStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="member" extends="struts-default" namespace="" >        

<action name="login" 

class="com.test.MemberAction" 

method="login">

<result name="error">/login.jsp</result>

<result name="success">/memberInfo.jsp</result>

</action>

<action name="logout"

class="com.test.MemberAction"

method="logout">

<result type="redirectAction">login.action</result>

</action>

<action name="memberInfo"

class="com.test.MemberAction" 

method="memberInfo">

<result>/memberInfo.jsp</result>

</action>

<action name="memberInsertForm">

<result>/memberInsertForm.jsp</result>

</action>

<action name="memberIDCheck"

class="com.test.MemberAction" 

method="memberIDCheck">

<result>/memberIDCheck.jsp</result>

</action>

<action name="memberList"

class="com.test.MemberAction" 

method="memberList">

<result>/memberList.jsp</result>

</action>

</package>

</struts>





//memberIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="member">


<typeAlias alias="mdto" type="com.test.MemberDTO"/>

<select id="login"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id# AND pw=encrypt(#pw#, #id#)

</select>

<select id="searchId"

parameterClass="mdto"

resultClass="mdto">

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade 

FROM jmember 

WHERE id=#id#

</select>



<select id="duplicateID"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id#

</select>

<select id="lists"

resultClass="mdto">

SELECT id, name, tel, email, grade

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate 

FROM jmember 

ORDER BY grade ASC, name ASC

</select>



</sqlMap>






//MemberAction.java

package com.test;


import java.util.List;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

public String memberIDCheck() {

HttpServletRequest req = ServletActionContext.getRequest();

String data = req.getParameter("data");

String result = "OK";

CommonDAO dao = CommonDAOImpl.getInstance();


dto.setId(data);

int returnValue = dao.getIntValue("member.duplicateID", dto);

if (returnValue == 1) {

result = "Cancel";

}

req.setAttribute("result", result);

return SUCCESS;

}

public String memberList() {

CommonDAO dao = CommonDAOImpl.getInstance();

List<Object> arrayList = dao.getListData("member.lists");

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("arrayList", arrayList);

return SUCCESS;

}

}





//memberList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function memberAdminRemove(url, uid) {

if (confirm("아이디 : "+uid+"\n\n선택한 회원의 정보를 삭제하시겠습니까?")) {

window.location.href=url+"?uid="+uid;

}

}

function memberList(obj) {

window.location.href="memberList.action?grade="+obj.value;

}

//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

function radioCheck() {

var radios = document.getElementsByName("radioGroup");

radios[0].checked = true;

}

//----------------------------

</script>


</head>

<body onload="radioCheck()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단]</h3>

<div>

<form>

<input type="radio" name="radioGroup" 

checked="checked" 

onclick="memberList(this)" value="0">전체

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="1">관리자

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="2">직원

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="3">학생

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="4">회원가입

</form>

<br>

</div>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="tName" width="100">아이디</td>

<td class="tName">이름</td>

<td class="tName" width="160">전화</td>

<td class="tName" width="160">이메일</td>

<td class="tName" width="80">등급</td>

<td class="tName" width="120">가입일</td>

<td class="tName" width="80"></td>

</tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="bDot">${dto.id}</td>

<td class="bDot">${dto.name}</td>

<td class="bDot">${dto.tel}</td>

<td class="bDot">${dto.email}</td>

<td class="bDot">${array[dto.grade-1]}</td>

<td class="bDot">${dto.wdate}</td>

<td class="bDot" style="font-size:9pt;"><a href="">[등급변경]</a><br><a href="">[회원삭제]</a></td>

</tr>

</c:forEach>

</table>

</div>

</div>


</body>

</html>




//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



--------------------------------------------------

문제) 상담 게시판에서 회원 명단 출력시 등급별(전체, 관리자, 직원, 학생, 회원가입)로 출력되도록 할 것.



--------------------------------------------------

상담 게시판에서 회원 수정(관리자 전용)


//memberList.jsp -> [회원수정] 메뉴 등록

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function memberAdminRemove(url, uid) {

if (confirm("아이디 : "+uid+"\n\n선택한 회원의 정보를 삭제하시겠습니까?")) {

window.location.href=url+"?uid="+uid;

}

}

function memberList(obj) {

window.location.href="memberList.action?grade="+obj.value;

}

//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

function radioCheck() {

var radios = document.getElementsByName("radioGroup");

radios[0].checked = true;

}

//----------------------------

</script>


</head>

<body onload="radioCheck()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단]</h3>

<div>

<form>

<input type="radio" name="radioGroup" 

checked="checked" 

onclick="memberList(this)" value="0">전체

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="1">관리자

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="2">직원

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="3">학생

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="4">회원가입

</form>

<br>

</div>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="tName" width="100">아이디</td>

<td class="tName">이름</td>

<td class="tName" width="160">전화</td>

<td class="tName" width="160">이메일</td>

<td class="tName" width="80">등급</td>

<td class="tName" width="120">가입일</td>

<td class="tName" width="80"></td>

</tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="bDot">${dto.id}</td>

<td class="bDot">${dto.name}</td>

<td class="bDot">${dto.tel}</td>

<td class="bDot">${dto.email}</td>

<td class="bDot">${array[dto.grade-1]}</td>

<td class="bDot">${dto.wdate}</td>

<td class="bDot" style="font-size:9pt;"><a href="adminUpdateForm.action?id=${dto.id}">[회원수정]</a><br><a href="">[회원삭제]</a></td>

</tr>

</c:forEach>

</table>

</div>

</div>


</body>

</html>




//memberStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="member" extends="struts-default" namespace="" >        

<action name="login" 

class="com.test.MemberAction" 

method="login">

<result name="error">/login.jsp</result>

<result name="success">/memberInfo.jsp</result>

</action>

<action name="logout"

class="com.test.MemberAction"

method="logout">

<result type="redirectAction">login.action</result>

</action>

<action name="memberInfo"

class="com.test.MemberAction" 

method="memberInfo">

<result>/memberInfo.jsp</result>

</action>

<action name="memberInsertForm">

<result>/memberInsertForm.jsp</result>

</action>

<action name="memberIDCheck"

class="com.test.MemberAction" 

method="memberIDCheck">

<result>/memberIDCheck.jsp</result>

</action>

<action name="memberList"

class="com.test.MemberAction" 

method="memberList">

<result>/memberList.jsp</result>

</action>

<action name="adminUpdateForm"

class="com.test.MemberAction" 

method="adminUpdateForm">

<result name="success">/adminUpdateForm.jsp</result>

<result name="error" type="redirectAction">login.action</result>

</action>

<action name="adminUpdate"

class="com.test.MemberAction" 

method="adminUpdate">

<result name="success" type="redirectAction">memberList.action</result>

<result name="error" type="redirectAction">login.action</result>

</action>

</package>

</struts>






//memberIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="member">


<typeAlias alias="mdto" type="com.test.MemberDTO"/>

<select id="login"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id# AND pw=encrypt(#pw#, #id#)

</select>

<select id="searchId"

parameterClass="mdto"

resultClass="mdto">

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade 

FROM jmember 

WHERE id=#id#

</select>



<select id="duplicateID"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id#

</select>

<select id="lists"

resultClass="mdto">

SELECT id, name, tel, email, grade

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate 

FROM jmember 

ORDER BY grade ASC, name ASC

</select>


<update id="adminModify"

parameterClass="mdto">

UPDATE jmember 

SET name=#name#, email=#email#, tel=#tel#, grade=#grade# 

WHERE id=#id#

</update>


</sqlMap>






//MemberAction.java

package com.test;


import java.sql.SQLException;

import java.util.List;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

public String memberIDCheck() {

HttpServletRequest req = ServletActionContext.getRequest();

String data = req.getParameter("data");

String result = "OK";

CommonDAO dao = CommonDAOImpl.getInstance();


dto.setId(data);

int returnValue = dao.getIntValue("member.duplicateID", dto);

if (returnValue == 1) {

result = "Cancel";

}

req.setAttribute("result", result);

return SUCCESS;

}

public String memberList() {

CommonDAO dao = CommonDAOImpl.getInstance();

List<Object> arrayList = dao.getListData("member.lists");

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("arrayList", arrayList);

return SUCCESS;

}

public String adminUpdateForm() {

HttpServletRequest req = ServletActionContext.getRequest();

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

return ERROR;

}

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}


public String adminUpdate() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("member.adminModify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}


}





//adminUpdateForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function adminUpdateFormSubmit() {

var adminUpdateForm = document.getElementById("adminUpdateForm");

adminUpdateForm.submit();

}

function radioCheck(idx) {

var radios = document.getElementsByName("grade");

radios[idx].checked = true;

}

</script>


</head>

<body onload="radioCheck(${dto.grade-1})">

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단_회원수정]</h3>

<form action="adminUpdate.action" method="post" id="adminUpdateForm">

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

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="250px">아이디</td>

<td class="bTitle">${dto.id}</td>

</tr>

<tr>

<td class="tName" width="250px">이름<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="name" name="name" value="${dto.name}"></td>

</tr>

<tr>

<td class="tName" width="250px">이메일<span style="font-size:9pt;">(100자 이내)</span></td>

<td class="bTitle"><input type="text" id="email" name="email" style="width:300px" value="${dto.email}"></td>

</tr>

<tr>

<td class="tName" width="250px">전화<span style="font-size:9pt;">(30자 이내)</span></td>

<td class="bTitle"><input type="text" id="tel" name="tel" style="width:300px" value="${dto.tel}"></td>

</tr>

<tr>

<td class="tName" width="250px">등급(${array[dto.grade-1]})</td>

<td class="bTitle">

<input type="radio" name="grade" value="1">관리자

<input type="radio" name="grade" value="2">직원

<input type="radio" name="grade" value="3">학생

<input type="radio" name="grade" value="4">회원가입

</td>

</tr>

</table>

<br><br>

<a href="javascript:adminUpdateFormSubmit()">[회원수정]</a>

<a href="memberList.action">[회원명단]</a>

</form>

</div>

</div>


</body>

</html>





//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



------------------------------------------------

상담 게시판 패스워드 변경 (사용자)


//memberInfo.jsp -> [패스워드변경] 메뉴에 링크 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>        

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function msg() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle">${dto.id}</td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle">${dto.name}</td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle">${dto.email}</td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle">${dto.tel}</td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle">${array[dto.grade-1]}</td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자, 직원 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1' || sessionScope.grade == '2'}">

<a href="memberList.action">[*회원명단]</a>

</c:if>


<a href="memberPWModifyForm.action">[패스워드변경]</a>

<a href="memberModifyForm.action">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>





//memberStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="member" extends="struts-default" namespace="" >        

<action name="login" 

class="com.test.MemberAction" 

method="login">

<result name="error">/login.jsp</result>

<result name="success">/memberInfo.jsp</result>

</action>

<action name="logout"

class="com.test.MemberAction"

method="logout">

<result type="redirectAction">login.action</result>

</action>

<action name="memberInfo"

class="com.test.MemberAction" 

method="memberInfo">

<result>/memberInfo.jsp</result>

</action>

<action name="memberInsertForm">

<result>/memberInsertForm.jsp</result>

</action>

<action name="memberIDCheck"

class="com.test.MemberAction" 

method="memberIDCheck">

<result>/memberIDCheck.jsp</result>

</action>

<action name="memberList"

class="com.test.MemberAction" 

method="memberList">

<result>/memberList.jsp</result>

</action>

<action name="adminUpdateForm"

class="com.test.MemberAction" 

method="adminUpdateForm">

<result name="success">/adminUpdateForm.jsp</result>

<result name="error" type="redirectAction">login.action</result>

</action>

<action name="adminUpdate"

class="com.test.MemberAction" 

method="adminUpdate">

<result name="success" type="redirectAction">memberList.action</result>

<result name="error" type="redirectAction">login.action</result>

</action>

<action name="memberPWModifyForm">

<result>/memberPWModifyForm.jsp</result>

</action>

<action name="memberPWModify"

class="com.test.MemberAction" 

method="memberPWModify">

<result name="success" type="redirectAction">memberInfo.action</result>

<result name="error">/memberPWModifyForm.jsp</result>

</action>

</package>

</struts>





//memberPWModifyForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<c:if test="${!empty error}">

<script type="text/javascript">

window.onload = msg;

function msg() {

alert("기존 패스워드가 틀렸습니다.");

}

</script>

</c:if>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[회원정보_패스워드변경]</h3>

<form action="memberPWModify.action" method="post" id="memberPwForm">

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="200px">*기존 패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg" style="color:red; display:none;">1~20자 이내 패스워드 입력해야 합니다.</span></td>

</tr>

<tr>

<td class="tName" width="200px">*새로운 패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="newpw" name="newpw"><span id="newpwMsg" style="color:red; display:none;">1~20자 이내 패스워드 입력해야 합니다.</span></td>

</tr>

</table>

<br><br>

<a href="javascript:memberPwFormSubmit()">[패스워드변경]</a>

<a href="memberInfo.action">[회원정보]</a>

</form>

</div>

</div>


</body>

</html>






//memberIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="member">


<typeAlias alias="mdto" type="com.test.MemberDTO"/>

<select id="login"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id# AND pw=encrypt(#pw#, #id#)

</select>

<select id="searchId"

parameterClass="mdto"

resultClass="mdto">

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade 

FROM jmember 

WHERE id=#id#

</select>



<select id="duplicateID"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id#

</select>

<select id="lists"

resultClass="mdto">

SELECT id, name, tel, email, grade

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate 

FROM jmember 

ORDER BY grade ASC, name ASC

</select>


<update id="adminModify"

parameterClass="mdto">

UPDATE jmember 

SET name=#name#, email=#email#, tel=#tel#, grade=#grade# 

WHERE id=#id#

</update>

<update id="pwModify"

parameterClass="java.util.Map">

UPDATE jmember 

SET pw=encrypt(#newpw#, #id#) 

WHERE pw=encrypt(#oldpw#, #id#) AND id=#id#

</update>


</sqlMap>






//MemberAction.java

package com.test;


import java.sql.SQLException;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

public String memberIDCheck() {

HttpServletRequest req = ServletActionContext.getRequest();

String data = req.getParameter("data");

String result = "OK";

CommonDAO dao = CommonDAOImpl.getInstance();


dto.setId(data);

int returnValue = dao.getIntValue("member.duplicateID", dto);

if (returnValue == 1) {

result = "Cancel";

}

req.setAttribute("result", result);

return SUCCESS;

}

public String memberList() {

CommonDAO dao = CommonDAOImpl.getInstance();

List<Object> arrayList = dao.getListData("member.lists");

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("arrayList", arrayList);

return SUCCESS;

}

public String adminUpdateForm() {

HttpServletRequest req = ServletActionContext.getRequest();

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

return ERROR;

}

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}


public String adminUpdate() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("member.adminModify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String memberPWModify() {

HttpServletRequest req = ServletActionContext.getRequest();

String pw = req.getParameter("pw");

String newpw = req.getParameter("newpw");

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

Map<String, Object> map = new HashMap<String, Object>();

map.put("id", id);

map.put("oldpw", pw);

map.put("newpw", newpw);

CommonDAO dao = CommonDAOImpl.getInstance();

try {

int result = dao.updateData("member.pwModify", map);

if (result == 0) {

req.setAttribute("error", "true");

return ERROR;

}

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}


}





//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action


WRITTEN BY
빨강꼬마

,

---------------------------------------------------------

상담 게시판  답변글 처리

- 답변글 목록 출력 및 내용 보기 페이지 작성



//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


//-----------------------------

//답변글 읽어오는 전용 변수 추가

private String rid;

public String getRid() {

return rid;

}


public void setRid(String rid) {

this.rid = rid;

}

//-----------------------------

public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


public String getTitle() {

return title;

}


public void setTitle(String title) {

this.title = title;

}


public String getContent() {

return content;

}


public void setContent(String content) {

this.content = content;

}


public String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}





//consultationIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="consultation">


<typeAlias alias="cdto" type="com.test.ConsultationDTO"/>

<!-- 페이지 처리 전, 답변글 처리 전 -->

<select id="lists" resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultation 

ORDER BY sid DESC

</select>

<insert id="add" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE)

</insert>

<select id="searchBySid" 

parameterClass="cdto"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

, rid

FROM consultation 

WHERE sid=#sid#

</select>

<select id="searchByPw"

parameterClass="cdto"

resultClass="Integer">

SELECT COUNT(sid) AS count 

FROM consultation 

WHERE sid=#sid# 

AND name=#name# 

AND pw=encrypt(#pw#, #name#)

</select>

<update id="modify"

parameterClass="cdto">

UPDATE consultation 

SET title=#title#

, content=#content#

, wdate=SYSDATE 

WHERE sid=#sid#

</update>

<delete id="remove" parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid#

</delete>

<insert id="adminReply" parameterClass="cdto">

INSERT INTO consultReply (rid, name, title, content, wdate) 

VALUES (consultReplySeq.nextval

, #name#

, #title#

, #content#

, SYSDATE)

</insert>

<update id="modifySidReply" parameterClass="cdto">

UPDATE consultation 

SET rid=consultReplySeq.currval 

WHERE sid=#sid#

</update>

<!-- 데이터가 아니라 문장의 일부인 경우는 $skey$ 형태로 표기할 것 -->

<select id="searchLists" 

parameterClass="java.util.Map"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

, rid

FROM consultation 

WHERE LOWER($skey$) LIKE '%%'||LOWER(#svalue#)||'%%' 

ORDER BY sid DESC

</select>

<!-- ////////////////////// -->

<!-- 페이지 처리 후 -->

<select id="pageLists"

parameterClass="java.util.Map"

resultClass="cdto">

<![CDATA[

SELECT * 

FROM pageListView 

WHERE rnum>=#start# AND rnum<=#end#

]]>

</select>

<select id="count"

resultClass="Integer">

SELECT COUNT(*) AS count 

FROM consultation

</select>

<!-- //////////////////// -->


<!-- //////////////////// -->

<!-- 답변글 읽어오는 전용 쿼리 추가 -->

<select id="searchByRid"

parameterClass="cdto"

resultClass="cdto">

SELECT rid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

FROM consultReply 

WHERE rid=#rid#

</select>

<!-- //////////////////// -->


</sqlMap>







//ConsultationAction.java

package com.test;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


import com.util.dao.*;


import java.sql.SQLException;

import java.util.*;


import javax.servlet.http.HttpServletRequest;


import org.apache.struts2.ServletActionContext;


public class ConsultationAction extends ActionSupport

implements Preparable, ModelDriven<ConsultationDTO> {

private static final long serialVersionUID = 1L;

private ConsultationDTO dto;


@Override

public ConsultationDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new ConsultationDTO();

}

public String consultList() {

HttpServletRequest req = ServletActionContext.getRequest();

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 5;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

CommonDAO dao = CommonDAOImpl.getInstance();

//페이지 처리 전

//List<Object> arrayList = dao.getListData("consultation.lists");

//--------------------------

//페이지 처리 후

recordCount = dao.getIntValue("consultation.count");

Map<String, Object> map = new HashMap<String, Object>();

map.put("start", start);

map.put("end", end);

List<Object> arrayList = dao.getListData("consultation.pageLists", map);

//--------------------------

//---------------------------

//페이지 처리 후

com.util.MyUtil myUtil = new com.util.MyUtil();

String pageUrl = "[1][2][3][4]...";

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.action");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

return SUCCESS;

}

public String consultInsert() {

CommonDAO dao = CommonDAOImpl.getInstance();

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

//-> iBatis는 자동 실행됨

//-----------------------------

try {

dao.insertData("consultation.add", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultView() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

//----------------------------------

//답변글 읽어오는 부분 추가

Object robj = null;

ConsultationDTO newdto = (ConsultationDTO)obj;

if (newdto.getRid() != null) {

robj = dao.getReadData("consultation.searchByRid", newdto);

}

//----------------------------------

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

req.setAttribute("rdto", robj);

return SUCCESS;

}

public String consultModifyForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}


}

}

public String consultModify() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("consultation.modify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultRemoveForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

try {

dao.deleteData("consultation.remove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}

}

public String adminReplyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String adminReply() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.insertUpdateData("consultation.adminReply"

,"consultation.modifySidReply" 

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultSearch() {

HttpServletRequest req = ServletActionContext.getRequest();

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");

CommonDAO dao = CommonDAOImpl.getInstance();

Map<String, String> map = new HashMap<String, String>();

map.put("skey", skey);

map.put("svalue", svalue);

List<Object> arrayList = dao.getListData("consultation.searchLists", map);

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

return SUCCESS;

}

}





//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

//JSP 코드 작성-> JSTL, EL로 대체

%>   

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_${title}]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="bDot">${dto.sid}</td>

<td class="bTitle">

<a href="consultView.action?sid=${dto.sid}">${dto.title}</a>

<%-- 댓글 있는 경우 댓글 갯수 출력 --%>

<%-- 

<c:if test="${dto.commentCount > 0}">

<span style="color:red; font-size:10pt;">[${dto.commentCount}]</span>

</c:if>

--%>

<%-- 답변글 있는 경우 [답변있음] 메시지 출력 --%>

<c:if test="${!empty dto.rid}">

<span style="color:blue; font-size:10pt;">[답변있음]</span>

</c:if>

</td>

<td class="bDot">${dto.name}</td>

<td class="bDot">${dto.wdate}</td>

</tr>

</c:forEach>


</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot">

<c:choose>

<c:when test="${empty pageUrl}"><br></c:when>

<c:otherwise>${pageUrl}</c:otherwise>

</c:choose>

</td>

</tr>

</table>

<form action="consultSearch.action" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey">

<c:choose>

<c:when test="${param.skey == 'title'}"><option value="title" selected="selected">제목</option></c:when>

<c:otherwise><option value="title">제목</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'content'}"><option value="content" selected="selected">내용</option></c:when>

<c:otherwise><option value="content">내용</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'name'}"><option value="name" selected="selected">글작성자</option></c:when>

<c:otherwise><option value="name">글작성자</option></c:otherwise>

</c:choose>

</select>

<input type="text" id="svalue" name="svalue" value="${param.svalue}">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<%-- 회원 로그인 여부에 따라서 다른 새글쓰기 메뉴 출력됨 --%>

<c:choose>

<c:when test="${empty sessionScope.id}"><a href="consultInsertForm.action">[새글쓰기]</a></c:when>

<c:otherwise><a href="consultMemberInsertForm.action">[새글쓰기]</a></c:otherwise>

</c:choose>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>




//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

pageContext.setAttribute("newLineChar", "\n");

pageContext.setAttribute("tabChar", "\t");

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. -->${fn:replace(fn:replace(dto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span><!-- 관리자 -->${fn:replace(fn:replace(dto.name, "<", "&lt;"), ">", "&gt;")}

<%--

<c:choose>

<c:when test="${empty dto.id}">(비회원)</c:when>

<c:otherwise>(${dto.id})</c:otherwise>

</c:choose>

--%>

</span>

<span><!-- 2010-01-01 -->${dto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(dto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3>${fn:replace(fn:replace(rdto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span>${fn:replace(fn:replace(rdto.name, "<", "&lt;"), ">", "&gt;")}</span>

<span>${rdto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(rdto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

</td>

</tr>

</table>

</div>

</c:if>

 

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<%--

<div style="margin-top:10px;font-size:10pt;">

 ${dto.commentCount} 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.action" method="post" id="commentInsertForm">

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

글쓴이 '${sessionScope.name}' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<c:forEach var="cdto" items="${commentLists}">

<tr>

<td>${cdto.name}</td>

<td>${cdto.title}</td>

<td>${cdto.wdate}</td>

<td>

<c:if test="${!empty sessionScope.id && cdto.id == sessionScope.id}">

<a href="">[삭제]</a>

</c:if>

</td>

</tr>

</c:forEach>

</table>

</div>

--%>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<%--

<c:if test="${sessionScope.grade == '1'}">

--%>

<a href="adminReplyForm.action?sid=${dto.sid}">[*답변글쓰기]</a>

<%--

</c:if>

--%>

 

<a href="consultList.action">[목록보기]</a>

<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<%--

<c:choose>

<c:when test="${empty sessionScope.id && empty dto.id}">

  --%>

 

<a href="consultModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="consultRemoveForm.action?sid=${dto.sid}">[글 삭제]</a>


<%--

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == dto.id}">

<a href="consultMemberModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="javascript:consultMemberDelete(${dto.sid})">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

--%>

<%-- ------------------------------- --%>


</div>

</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action




----------------------------------------------------

관리자 로그인, 로그아웃

-> 서블릿 주소를 *.action 으로 처리함.



//MemberDTO.java

package com.test;


public class MemberDTO {

private String id, pw, name, email, tel, wdate;

private int grade;


public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getPw() {

return pw;

}

public void setPw(String pw) {

this.pw = pw;

}

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 getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}

public String getWdate() {

return wdate;

}

public void setWdate(String wdate) {

this.wdate = wdate;

}

public int getGrade() {

return grade;

}

public void setGrade(int grade) {

this.grade = grade;

}

}





//memberIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="member">


<typeAlias alias="mdto" type="com.test.MemberDTO"/>

<select id="login"

parameterClass="mdto"

resultClass="Integer">

SELECT COUNT(*) AS count

FROM jmember 

WHERE id=#id# AND pw=encrypt(#pw#, #id#)

</select>

<select id="searchId"

parameterClass="mdto"

resultClass="mdto">

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade 

FROM jmember 

WHERE id=#id#

</select>


</sqlMap>






//sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMapConfig      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">


<sqlMapConfig>


  <settings

    cacheModelsEnabled="false"

    useStatementNamespaces="true"/>


  <!-- Configure a built-in transaction manager.  If you're using an 

       app server, you probably want to use its transaction manager 

       and a managed datasource -->

   <transactionManager type="JDBC" commitRequired="false">

      <dataSource type="SIMPLE">

         <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>

         <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@220.76.176.101:1521:xe"/>

         <property name="JDBC.Username" value="scott"/>

         <property name="JDBC.Password" value="tiger"/>

      </dataSource>

  </transactionManager>


  <!-- List the SQL Map XML files. They can be loaded from the 

       classpath, as they are here (com.domain.data...) -->

  

  <sqlMap resource="com/util/sqlMap/consultationIbatis.xml"/>

  <sqlMap resource="com/util/sqlMap/memberIbatis.xml"/>

  

  <!-- List more here...

  <sqlMap resource="com/mydomain/data/Order.xml"/>

  <sqlMap resource="com/mydomain/data/Documents.xml"/>

  -->


</sqlMapConfig>





//memberStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="member" extends="struts-default" namespace="" >        

<action name="login" 

class="com.test.MemberAction" 

method="login">

<result name="error">/login.jsp</result>

<result name="success">/memberInfo.jsp</result>

</action>

<action name="logout"

class="com.test.MemberAction"

method="logout">

<result type="redirectAction">login.action</result>

</action>

<action name="memberInfo" 

class="com.test.MemberAction" 

method="memberInfo">

<result>/memberInfo.jsp</result>

</action>

</package>

</struts>






//struts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

   <!-- Configuration for the default package. -->

    <package name="default" extends="struts-default" namespace="" >        

        <global-results>

            <result name="error">/exception/error.jsp</result>

        </global-results>

   </package>

   

   <include file="consultationStruts.xml"></include>

   <include file="memberStruts.xml"></include>


</struts>





//MemberAction.java

package com.test;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

}




//login.jsp

package com.test;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.util.dao.CommonDAO;

import com.util.dao.CommonDAOImpl;


public class MemberAction extends ActionSupport

implements Preparable, ModelDriven<MemberDTO> {

private static final long serialVersionUID = 1L;


private MemberDTO dto;


@Override

public MemberDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new MemberDTO();

}

public String login() {

if (dto.getId() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("member.login", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("member.searchId", dto);

HttpServletRequest req = ServletActionContext.getRequest();

MemberDTO newdto = (MemberDTO)obj;

HttpSession session = req.getSession();

session.setAttribute("id", newdto.getId());

session.setAttribute("name", newdto.getName());

session.setAttribute("grade", newdto.getGrade());

req.setAttribute("dto", obj);

return SUCCESS;

}


}


}


public String logout() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

session.invalidate();

return SUCCESS;

}


public String memberInfo() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

dto.setId(id);

Object obj = dao.getReadData("member.searchId", dto);

req.setAttribute("dto", obj);

return SUCCESS;

}

}





//memberInfo.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};

request.setAttribute("array", array);

%>        

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function msg() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle">${dto.id}</td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle">${dto.name}</td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle">${dto.email}</td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle">${dto.tel}</td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle">${array[dto.grade-1]}</td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자, 직원 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1' || sessionScope.grade == '2'}">

<a href="memberList.action">[*회원명단]</a>

</c:if>


<a href="memberPWModifyForm.action">[패스워드변경]</a>

<a href="memberModifyForm.action">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>





//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

pageContext.setAttribute("newLineChar", "\n");

pageContext.setAttribute("tabChar", "\t");

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. -->${fn:replace(fn:replace(dto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span><!-- 관리자 -->${fn:replace(fn:replace(dto.name, "<", "&lt;"), ">", "&gt;")}

<%--

<c:choose>

<c:when test="${empty dto.id}">(비회원)</c:when>

<c:otherwise>(${dto.id})</c:otherwise>

</c:choose>

--%>

</span>

<span><!-- 2010-01-01 -->${dto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(dto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3>${fn:replace(fn:replace(rdto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span>${fn:replace(fn:replace(rdto.name, "<", "&lt;"), ">", "&gt;")}</span>

<span>${rdto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(rdto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

</td>

</tr>

</table>

</div>

</c:if>

 

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<%--

<div style="margin-top:10px;font-size:10pt;">

 ${dto.commentCount} 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.action" method="post" id="commentInsertForm">

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

글쓴이 '${sessionScope.name}' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<c:forEach var="cdto" items="${commentLists}">

<tr>

<td>${cdto.name}</td>

<td>${cdto.title}</td>

<td>${cdto.wdate}</td>

<td>

<c:if test="${!empty sessionScope.id && cdto.id == sessionScope.id}">

<a href="">[삭제]</a>

</c:if>

</td>

</tr>

</c:forEach>

</table>

</div>

--%>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.action?sid=${dto.sid}">[*답변글쓰기]</a>

</c:if>

 

<a href="consultList.action">[목록보기]</a>

<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<%--

<c:choose>

<c:when test="${empty sessionScope.id && empty dto.id}">

  --%>

 

<a href="consultModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="consultRemoveForm.action?sid=${dto.sid}">[글 삭제]</a>


<%--

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == dto.id}">

<a href="consultMemberModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="javascript:consultMemberDelete(${dto.sid})">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

--%>

<%-- ------------------------------- --%>


</div>

</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



----------------------------------------

상담 게시판 댓글 쓰기 (로그인한 사용자만 댓글 쓰기 가능)



//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

pageContext.setAttribute("newLineChar", "\n");

pageContext.setAttribute("tabChar", "\t");

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. -->${fn:replace(fn:replace(dto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span><!-- 관리자 -->${fn:replace(fn:replace(dto.name, "<", "&lt;"), ">", "&gt;")}

<%--

<c:choose>

<c:when test="${empty dto.id}">(비회원)</c:when>

<c:otherwise>(${dto.id})</c:otherwise>

</c:choose>

--%>

</span>

<span><!-- 2010-01-01 -->${dto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(dto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3>${fn:replace(fn:replace(rdto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span>${fn:replace(fn:replace(rdto.name, "<", "&lt;"), ">", "&gt;")}</span>

<span>${rdto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(rdto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

</td>

</tr>

</table>

</div>

</c:if>

 

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 ${dto.commentCount} 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.action" method="post" id="commentInsertForm">

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

글쓴이 '${sessionScope.name}' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<c:forEach var="cdto" items="${commentLists}">

<tr>

<td>${cdto.name}</td>

<td>${cdto.title}</td>

<td>${cdto.wdate}</td>

<td>

<c:if test="${!empty sessionScope.id && cdto.id == sessionScope.id}">

<a href="">[삭제]</a>

</c:if>

</td>

</tr>

</c:forEach>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.action?sid=${dto.sid}">[*답변글쓰기]</a>

</c:if>

 

<a href="consultList.action">[목록보기]</a>

<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<%--

<c:choose>

<c:when test="${empty sessionScope.id && empty dto.id}">

  --%>

 

<a href="consultModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="consultRemoveForm.action?sid=${dto.sid}">[글 삭제]</a>


<%--

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == dto.id}">

<a href="consultMemberModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="javascript:consultMemberDelete(${dto.sid})">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

--%>

<%-- ------------------------------- --%>


</div>

</div>

</div>

</body>

</html>





//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


//-----------------------------

//답변글 읽어오는 전용 변수 추가

private String rid;

public String getRid() {

return rid;

}


public void setRid(String rid) {

this.rid = rid;

}

//-----------------------------

//-------------------------------

//댓글 처리를 위한 id 변수 추가

private String id;

public String getId() {

return id;

}


public void setId(String id) {

this.id = id;

}


//댓글 처리를 위한 commentCount 변수 추가

private int commentCount;

public int getCommentCount() {

return commentCount;

}


public void setCommentCount(int commentCount) {

this.commentCount = commentCount;

}

//댓글 처리를 위한 cid 변수 추가

private String cid;

public String getCid() {

return cid;

}

public void setCid(String cid) {

this.cid = cid;

}

//-------------------------------


public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


public String getTitle() {

return title;

}


public void setTitle(String title) {

this.title = title;

}


public String getContent() {

return content;

}


public void setContent(String content) {

this.content = content;

}


public String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}





//consultationStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="consultation" extends="struts-default" namespace="" >

<!-- 상담게시판 글목록 출력 -->        

<action name="consultList" 

class="com.test.ConsultationAction" 

method="consultList">

<result>/consultList.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 화면 출력 -->

<action name="consultInsertForm">

<result>/consultInsertForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 액션 처리 -->

<action name="consultInsert"

class="com.test.ConsultationAction"

method="consultInsert">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 내용보기 액션 처리 -->

<action name="consultView"

class="com.test.ConsultationAction"

method="consultView">

<result>/consultView.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 화면 출력 --> 

<action name="consultModifyForm"

class="com.test.ConsultationAction"

method="consultModifyForm">

<result name="error">/consultPW.jsp</result>

<result name="success">/consultModifyForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 액션 처리 --> 

<action name="consultModify"

class="com.test.ConsultationAction"

method="consultModify">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>


<!-- 상담게시판 비회원 글 삭제 액션 처리 --> 

<action name="consultRemoveForm"

class="com.test.ConsultationAction"

method="consultRemoveForm">

<result name="error">/consultPW.jsp</result>

<result name="success" type="redirectAction">consultList.action</result>

</action>



<!-- 상담게시판 답변글 입력 화면 출력(관리자 전용) -->

<action name="adminReplyForm"

class="com.test.ConsultationAction"

method="adminReplyForm">

<result>/adminReplyForm.jsp</result>

</action>

<!-- 상담게시판 답변글 입력 액션 처리(관리자 전용) -->

<action name="adminReply"

class="com.test.ConsultationAction"

method="adminReply">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 검색 액션 처리 -->

<action name="consultSearch" 

class="com.test.ConsultationAction" 

method="consultSearch">

<result>/consultList.jsp</result>

</action>

<!-- 댓글 입력 액션 처리 -->

<action name="commentInsert"

class="com.test.ConsultationAction"

method="commentInsert">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>


</package>

</struts>





//consultationIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="consultation">


<typeAlias alias="cdto" type="com.test.ConsultationDTO"/>

<!-- 페이지 처리 전, 답변글 처리 전 -->

<select id="lists" resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultation 

ORDER BY sid DESC

</select>

<insert id="add" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE)

</insert>

<select id="searchBySid" 

parameterClass="cdto"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

, rid

FROM consultation 

WHERE sid=#sid#

</select>

<select id="searchByPw"

parameterClass="cdto"

resultClass="Integer">

SELECT COUNT(sid) AS count 

FROM consultation 

WHERE sid=#sid# 

AND name=#name# 

AND pw=encrypt(#pw#, #name#)

</select>

<update id="modify"

parameterClass="cdto">

UPDATE consultation 

SET title=#title#

, content=#content#

, wdate=SYSDATE 

WHERE sid=#sid#

</update>

<delete id="remove" parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid#

</delete>

<insert id="adminReply" parameterClass="cdto">

INSERT INTO consultReply (rid, name, title, content, wdate) 

VALUES (consultReplySeq.nextval

, #name#

, #title#

, #content#

, SYSDATE)

</insert>

<update id="modifySidReply" parameterClass="cdto">

UPDATE consultation 

SET rid=consultReplySeq.currval 

WHERE sid=#sid#

</update>

<!-- 데이터가 아니라 문장의 일부인 경우는 $skey$ 형태로 표기할 것 -->

<select id="searchLists" 

parameterClass="java.util.Map"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

, rid

FROM consultation 

WHERE LOWER($skey$) LIKE '%%'||LOWER(#svalue#)||'%%' 

ORDER BY sid DESC

</select>

<!-- ////////////////////////// -->

<!-- 페이지 처리 후 -->

<select id="pageLists"

parameterClass="java.util.Map"

resultClass="cdto">

<![CDATA[

SELECT * 

FROM pageListView 

WHERE rnum>=#start# AND rnum<=#end#

]]>

</select>

<select id="count"

resultClass="Integer">

SELECT COUNT(*) AS count 

FROM consultation

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 답변글 읽어오는 전용 쿼리 추가 -->

<select id="searchByRid"

parameterClass="cdto"

resultClass="cdto">

SELECT rid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

FROM consultReply 

WHERE rid=#rid#

</select>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 입력용 쿼리 -->

<insert id="commentAdd"

parameterClass="cdto">

INSERT INTO consultComment (cid, id, name, title, wdate, sid) 

VALUES (consultCommentSeq.nextval

, #id#

, #name#

, #title#

, SYSDATE

, #sid#)

</insert>

<update id="commentCountIncrease"

parameterClass="cdto">

UPDATE consultation 

SET commentCount = commentCount + 1 

WHERE sid=#sid#

</update>

<!-- //////////////////// -->


</sqlMap>






//ConsultationAction.java

package com.test;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


import com.util.dao.*;


import java.sql.SQLException;

import java.util.*;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


public class ConsultationAction extends ActionSupport

implements Preparable, ModelDriven<ConsultationDTO> {

private static final long serialVersionUID = 1L;

private ConsultationDTO dto;


@Override

public ConsultationDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new ConsultationDTO();

}

public String consultList() {

HttpServletRequest req = ServletActionContext.getRequest();

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 5;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

CommonDAO dao = CommonDAOImpl.getInstance();

//페이지 처리 전

//List<Object> arrayList = dao.getListData("consultation.lists");

//--------------------------

//페이지 처리 후

recordCount = dao.getIntValue("consultation.count");

Map<String, Object> map = new HashMap<String, Object>();

map.put("start", start);

map.put("end", end);

List<Object> arrayList = dao.getListData("consultation.pageLists", map);

//--------------------------

//---------------------------

//페이지 처리 후

com.util.MyUtil myUtil = new com.util.MyUtil();

String pageUrl = "[1][2][3][4]...";

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.action");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

return SUCCESS;

}

public String consultInsert() {

CommonDAO dao = CommonDAOImpl.getInstance();

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

//-> iBatis는 자동 실행됨

//-----------------------------

try {

dao.insertData("consultation.add", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultView() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

//----------------------------------

//답변글 읽어오는 부분 추가

Object robj = null;

ConsultationDTO newdto = (ConsultationDTO)obj;

if (newdto.getRid() != null) {

robj = dao.getReadData("consultation.searchByRid", newdto);

}

//----------------------------------

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

req.setAttribute("rdto", robj);

return SUCCESS;

}

public String consultModifyForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}


}

}

public String consultModify() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("consultation.modify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultRemoveForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

try {

dao.deleteData("consultation.remove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}

}

public String adminReplyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String adminReply() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.insertUpdateData("consultation.adminReply"

,"consultation.modifySidReply" 

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultSearch() {

HttpServletRequest req = ServletActionContext.getRequest();

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");

CommonDAO dao = CommonDAOImpl.getInstance();

Map<String, String> map = new HashMap<String, String>();

map.put("skey", skey);

map.put("svalue", svalue);

List<Object> arrayList = dao.getListData("consultation.searchLists", map);

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

return SUCCESS;

}

public String commentInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setId(id);

dto.setName(name);

dao.insertUpdateData("consultation.commentAdd"

, "consultation.commentCountIncrease"

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}





//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



--------------------------------------------------------

상담 게시판 댓글 출력



//consultationIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="consultation">


<typeAlias alias="cdto" type="com.test.ConsultationDTO"/>

<!-- 페이지 처리 전, 답변글 처리 전, 댓글 출력 전 -->

<select id="lists" resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultation 

ORDER BY sid DESC

</select>

<insert id="add" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE)

</insert>

<select id="searchBySid" 

parameterClass="cdto"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

, rid

, commentCount

FROM consultation

WHERE sid=#sid#

</select>

<select id="searchByPw"

parameterClass="cdto"

resultClass="Integer">

SELECT COUNT(sid) AS count 

FROM consultation 

WHERE sid=#sid# 

AND name=#name# 

AND pw=encrypt(#pw#, #name#)

</select>

<update id="modify"

parameterClass="cdto">

UPDATE consultation 

SET title=#title#

, content=#content#

, wdate=SYSDATE 

WHERE sid=#sid#

</update>

<delete id="remove" parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid#

</delete>

<insert id="adminReply" parameterClass="cdto">

INSERT INTO consultReply (rid, name, title, content, wdate) 

VALUES (consultReplySeq.nextval

, #name#

, #title#

, #content#

, SYSDATE)

</insert>

<update id="modifySidReply" parameterClass="cdto">

UPDATE consultation 

SET rid=consultReplySeq.currval 

WHERE sid=#sid#

</update>

<!-- 데이터가 아니라 문장의 일부인 경우는 $skey$ 형태로 표기할 것 -->

<select id="searchLists" 

parameterClass="java.util.Map"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

, rid

, commentCount

FROM consultation 

WHERE LOWER($skey$) LIKE '%%'||LOWER(#svalue#)||'%%' 

ORDER BY sid DESC

</select>

<!-- ////////////////////////// -->

<!-- 페이지 처리 후 -->

<select id="pageLists"

parameterClass="java.util.Map"

resultClass="cdto">

<![CDATA[

SELECT * 

FROM pageListView 

WHERE rnum>=#start# AND rnum<=#end#

]]>

</select>

<select id="count"

resultClass="Integer">

SELECT COUNT(*) AS count 

FROM consultation

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 답변글 읽어오는 전용 쿼리 추가 -->

<select id="searchByRid"

parameterClass="cdto"

resultClass="cdto">

SELECT rid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

FROM consultReply 

WHERE rid=#rid#

</select>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 입력용 쿼리 -->

<insert id="commentAdd"

parameterClass="cdto">

INSERT INTO consultComment (cid, id, name, title, wdate, sid) 

VALUES (consultCommentSeq.nextval

, #id#

, #name#

, #title#

, SYSDATE

, #sid#)

</insert>

<update id="commentCountIncrease"

parameterClass="cdto">

UPDATE consultation 

SET commentCount = commentCount + 1 

WHERE sid=#sid#

</update>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 목록 읽어오는 쿼리 -->

<select id="commentLists"

parameterClass="cdto"

resultClass="cdto">

SELECT cid, id, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultComment 

WHERE sid=#sid# 

ORDER BY cid ASC

</select>

<!-- //////////////////// -->


</sqlMap>






//ConsultationAction.java

package com.test;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


import com.util.dao.*;


import java.sql.SQLException;

import java.util.*;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


public class ConsultationAction extends ActionSupport

implements Preparable, ModelDriven<ConsultationDTO> {

private static final long serialVersionUID = 1L;

private ConsultationDTO dto;


@Override

public ConsultationDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new ConsultationDTO();

}

public String consultList() {

HttpServletRequest req = ServletActionContext.getRequest();

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 5;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

CommonDAO dao = CommonDAOImpl.getInstance();

//페이지 처리 전

//List<Object> arrayList = dao.getListData("consultation.lists");

//--------------------------

//페이지 처리 후

recordCount = dao.getIntValue("consultation.count");

Map<String, Object> map = new HashMap<String, Object>();

map.put("start", start);

map.put("end", end);

List<Object> arrayList = dao.getListData("consultation.pageLists", map);

//--------------------------

//---------------------------

//페이지 처리 후

com.util.MyUtil myUtil = new com.util.MyUtil();

String pageUrl = "[1][2][3][4]...";

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.action");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

return SUCCESS;

}

public String consultInsert() {

CommonDAO dao = CommonDAOImpl.getInstance();

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

//-> iBatis는 자동 실행됨

//-----------------------------

try {

dao.insertData("consultation.add", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultView() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

//----------------------------------

//답변글 읽어오는 부분 추가

Object robj = null;

ConsultationDTO newdto = (ConsultationDTO)obj;

if (newdto.getRid() != null) {

robj = dao.getReadData("consultation.searchByRid", newdto);

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

List<Object> arrayList = null;

if (newdto.getCommentCount() > 0) {

arrayList = dao.getListData("consultation.commentLists"

, dto);

}

//----------------------------------

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

req.setAttribute("rdto", robj);

req.setAttribute("commentLists", arrayList);

return SUCCESS;

}

public String consultModifyForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}


}

}

public String consultModify() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("consultation.modify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultRemoveForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

try {

dao.deleteData("consultation.remove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}

}

public String adminReplyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String adminReply() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.insertUpdateData("consultation.adminReply"

,"consultation.modifySidReply" 

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultSearch() {

HttpServletRequest req = ServletActionContext.getRequest();

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");

CommonDAO dao = CommonDAOImpl.getInstance();

Map<String, String> map = new HashMap<String, String>();

map.put("skey", skey);

map.put("svalue", svalue);

List<Object> arrayList = dao.getListData("consultation.searchLists", map);

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

return SUCCESS;

}

public String commentInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setId(id);

dto.setName(name);

dao.insertUpdateData("consultation.commentAdd"

, "consultation.commentCountIncrease"

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}





//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

//JSP 코드 작성-> JSTL, EL로 대체

%>   

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_${title}]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="bDot">${dto.sid}</td>

<td class="bTitle">

<a href="consultView.action?sid=${dto.sid}">${dto.title}</a>

<%-- 댓글 있는 경우 댓글 갯수 출력 --%>

<c:if test="${dto.commentCount > 0}">

<span style="color:red; font-size:10pt;">[${dto.commentCount}]</span>

</c:if>

<%-- 답변글 있는 경우 [답변있음] 메시지 출력 --%>

<c:if test="${!empty dto.rid}">

<span style="color:blue; font-size:10pt;">[답변있음]</span>

</c:if>

</td>

<td class="bDot">${dto.name}</td>

<td class="bDot">${dto.wdate}</td>

</tr>

</c:forEach>


</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot">

<c:choose>

<c:when test="${empty pageUrl}"><br></c:when>

<c:otherwise>${pageUrl}</c:otherwise>

</c:choose>

</td>

</tr>

</table>

<form action="consultSearch.action" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey">

<c:choose>

<c:when test="${param.skey == 'title'}"><option value="title" selected="selected">제목</option></c:when>

<c:otherwise><option value="title">제목</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'content'}"><option value="content" selected="selected">내용</option></c:when>

<c:otherwise><option value="content">내용</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'name'}"><option value="name" selected="selected">글작성자</option></c:when>

<c:otherwise><option value="name">글작성자</option></c:otherwise>

</c:choose>

</select>

<input type="text" id="svalue" name="svalue" value="${param.svalue}">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<%-- 회원 로그인 여부에 따라서 다른 새글쓰기 메뉴 출력됨 --%>

<c:choose>

<c:when test="${empty sessionScope.id}"><a href="consultInsertForm.action">[새글쓰기]</a></c:when>

<c:otherwise><a href="consultMemberInsertForm.action">[새글쓰기]</a></c:otherwise>

</c:choose>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

pageContext.setAttribute("newLineChar", "\n");

pageContext.setAttribute("tabChar", "\t");

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. -->${fn:replace(fn:replace(dto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span><!-- 관리자 -->${fn:replace(fn:replace(dto.name, "<", "&lt;"), ">", "&gt;")}

<%--

<c:choose>

<c:when test="${empty dto.id}">(비회원)</c:when>

<c:otherwise>(${dto.id})</c:otherwise>

</c:choose>

--%>

</span>

<span><!-- 2010-01-01 -->${dto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(dto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3>${fn:replace(fn:replace(rdto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span>${fn:replace(fn:replace(rdto.name, "<", "&lt;"), ">", "&gt;")}</span>

<span>${rdto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(rdto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

</td>

</tr>

</table>

</div>

</c:if>

 

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 ${dto.commentCount} 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.action" method="post" id="commentInsertForm">

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

글쓴이 '${sessionScope.name}' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<c:forEach var="cdto" items="${commentLists}">

<tr>

<td>${cdto.name}</td>

<td>${cdto.title}</td>

<td>${cdto.wdate}</td>

<td>

<c:if test="${!empty sessionScope.id && cdto.id == sessionScope.id}">

<a href="">[삭제]</a>

</c:if>

</td>

</tr>

</c:forEach>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.action?sid=${dto.sid}">[*답변글쓰기]</a>

</c:if>

 

<a href="consultList.action">[목록보기]</a>

<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<%--

<c:choose>

<c:when test="${empty sessionScope.id && empty dto.id}">

  --%>

 

<a href="consultModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="consultRemoveForm.action?sid=${dto.sid}">[글 삭제]</a>


<%--

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == dto.id}">

<a href="consultMemberModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="javascript:consultMemberDelete(${dto.sid})">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

--%>

<%-- ------------------------------- --%>


</div>

</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



--------------------------------------------------------

문제) 상담 게시판 댓글 삭제 (로그인한 사용자가 본인이 쓴 댓글만 삭제 가능)




--------------------------------------------------------

상담 게시판 회원 글쓰기(로그인한 사용자인 경우)



//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

//JSP 코드 작성-> JSTL, EL로 대체

%>   

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_${title}]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<c:forEach var="dto" items="${arrayList}">

<tr>

<td class="bDot">${dto.sid}</td>

<td class="bTitle">

<a href="consultView.action?sid=${dto.sid}">${dto.title}</a>

<%-- 댓글 있는 경우 댓글 갯수 출력 --%>

<c:if test="${dto.commentCount > 0}">

<span style="color:red; font-size:10pt;">[${dto.commentCount}]</span>

</c:if>

<%-- 답변글 있는 경우 [답변있음] 메시지 출력 --%>

<c:if test="${!empty dto.rid}">

<span style="color:blue; font-size:10pt;">[답변있음]</span>

</c:if>

</td>

<td class="bDot">${dto.name}</td>

<td class="bDot">${dto.wdate}</td>

</tr>

</c:forEach>


</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot">

<c:choose>

<c:when test="${empty pageUrl}"><br></c:when>

<c:otherwise>${pageUrl}</c:otherwise>

</c:choose>

</td>

</tr>

</table>

<form action="consultSearch.action" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey">

<c:choose>

<c:when test="${param.skey == 'title'}"><option value="title" selected="selected">제목</option></c:when>

<c:otherwise><option value="title">제목</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'content'}"><option value="content" selected="selected">내용</option></c:when>

<c:otherwise><option value="content">내용</option></c:otherwise>

</c:choose>

<c:choose>

<c:when test="${param.skey == 'name'}"><option value="name" selected="selected">글작성자</option></c:when>

<c:otherwise><option value="name">글작성자</option></c:otherwise>

</c:choose>

</select>

<input type="text" id="svalue" name="svalue" value="${param.svalue}">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<%-- 회원 로그인 여부에 따라서 다른 새글쓰기 메뉴 출력됨 --%>

<c:choose>

<c:when test="${empty sessionScope.id}"><a href="consultInsertForm.action">[새글쓰기]</a></c:when>

<c:otherwise><a href="consultMemberInsertForm.action">[새글쓰기]</a></c:otherwise>

</c:choose>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//consultationStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="consultation" extends="struts-default" namespace="" >

<!-- 상담게시판 글목록 출력 -->        

<action name="consultList" 

class="com.test.ConsultationAction" 

method="consultList">

<result>/consultList.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 화면 출력 -->

<action name="consultInsertForm">

<result>/consultInsertForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 액션 처리 -->

<action name="consultInsert"

class="com.test.ConsultationAction"

method="consultInsert">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 내용보기 액션 처리 -->

<action name="consultView"

class="com.test.ConsultationAction"

method="consultView">

<result>/consultView.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 화면 출력 --> 

<action name="consultModifyForm"

class="com.test.ConsultationAction"

method="consultModifyForm">

<result name="error">/consultPW.jsp</result>

<result name="success">/consultModifyForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 액션 처리 --> 

<action name="consultModify"

class="com.test.ConsultationAction"

method="consultModify">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>


<!-- 상담게시판 비회원 글 삭제 액션 처리 --> 

<action name="consultRemoveForm"

class="com.test.ConsultationAction"

method="consultRemoveForm">

<result name="error">/consultPW.jsp</result>

<result name="success" type="redirectAction">consultList.action</result>

</action>



<!-- 상담게시판 답변글 입력 화면 출력(관리자 전용) -->

<action name="adminReplyForm"

class="com.test.ConsultationAction"

method="adminReplyForm">

<result>/adminReplyForm.jsp</result>

</action>

<!-- 상담게시판 답변글 입력 액션 처리(관리자 전용) -->

<action name="adminReply"

class="com.test.ConsultationAction"

method="adminReply">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 검색 액션 처리 -->

<action name="consultSearch" 

class="com.test.ConsultationAction" 

method="consultSearch">

<result>/consultList.jsp</result>

</action>

<!-- 댓글 입력 액션 처리 -->

<action name="commentInsert"

class="com.test.ConsultationAction"

method="commentInsert">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>

<!-- 회원 전용 글쓰기 입력 화면 -->

<action name="consultMemberInsertForm">

<result>/consultMemberInsertForm.jsp</result>

</action>

<!-- 회원 전용 글쓰기 액션 처리 -->

<action name="consultMemberInsert"

class="com.test.ConsultationAction"

method="consultMemberInsert">

<result type="redirectAction">consultList.action</result>

</action>


</package>

</struts>






//consultMemberInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_글쓰기]</h3>

<form action="consultMemberInsert.action" method="post" id="consultInsertForm">

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="100">제목*</td>

<td class="bTitle"><input type="text" style="width:600px;" id="title" name="title"><span id="titleMsg" style="color:red; display:none;">1~100자 제목 입력</span></td>

</tr>

<tr>

<td class="tName" width="100">내용</td>

<td class="bTitle"><textarea style="width:600px;height:200px;" id="content" name="content"></textarea></td>

</tr>

</table>

<table>

<tr>

<td>

<a href="javascript:consultMemberInsertSubmit()">[글쓰기]</a>

<a href="javascript:consultInsertReset()">[새로작성]</a>

<a href="consultList.action">[목록보기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//cosultationIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="consultation">


<typeAlias alias="cdto" type="com.test.ConsultationDTO"/>

<!-- 페이지 처리 전, 답변글 처리 전, 댓글 출력 전 -->

<select id="lists" resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultation 

ORDER BY sid DESC

</select>

<insert id="add" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE)

</insert>

<select id="searchBySid" 

parameterClass="cdto"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

, rid

, commentCount

FROM consultation

WHERE sid=#sid#

</select>

<select id="searchByPw"

parameterClass="cdto"

resultClass="Integer">

SELECT COUNT(sid) AS count 

FROM consultation 

WHERE sid=#sid# 

AND name=#name# 

AND pw=encrypt(#pw#, #name#)

</select>

<update id="modify"

parameterClass="cdto">

UPDATE consultation 

SET title=#title#

, content=#content#

, wdate=SYSDATE 

WHERE sid=#sid#

</update>

<delete id="remove" parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid#

</delete>

<insert id="adminReply" parameterClass="cdto">

INSERT INTO consultReply (rid, name, title, content, wdate) 

VALUES (consultReplySeq.nextval

, #name#

, #title#

, #content#

, SYSDATE)

</insert>

<update id="modifySidReply" parameterClass="cdto">

UPDATE consultation 

SET rid=consultReplySeq.currval 

WHERE sid=#sid#

</update>

<!-- 데이터가 아니라 문장의 일부인 경우는 $skey$ 형태로 표기할 것 -->

<select id="searchLists" 

parameterClass="java.util.Map"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

, rid

, commentCount

FROM consultation 

WHERE LOWER($skey$) LIKE '%%'||LOWER(#svalue#)||'%%' 

ORDER BY sid DESC

</select>

<!-- ////////////////////////// -->

<!-- 페이지 처리 후 -->

<select id="pageLists"

parameterClass="java.util.Map"

resultClass="cdto">

<![CDATA[

SELECT * 

FROM pageListView 

WHERE rnum>=#start# AND rnum<=#end#

]]>

</select>

<select id="count"

resultClass="Integer">

SELECT COUNT(*) AS count 

FROM consultation

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 답변글 읽어오는 전용 쿼리 추가 -->

<select id="searchByRid"

parameterClass="cdto"

resultClass="cdto">

SELECT rid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

FROM consultReply 

WHERE rid=#rid#

</select>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 입력용 쿼리 -->

<insert id="commentAdd"

parameterClass="cdto">

INSERT INTO consultComment (cid, id, name, title, wdate, sid) 

VALUES (consultCommentSeq.nextval

, #id#

, #name#

, #title#

, SYSDATE

, #sid#)

</insert>

<update id="commentCountIncrease"

parameterClass="cdto">

UPDATE consultation 

SET commentCount = commentCount + 1 

WHERE sid=#sid#

</update>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 목록 읽어오는 쿼리 -->

<select id="commentLists"

parameterClass="cdto"

resultClass="cdto">

SELECT cid, id, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultComment 

WHERE sid=#sid# 

ORDER BY cid ASC

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 회원 전용 글쓰기 쿼리 --> 

<insert id="memberAdd" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate, id) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE

,#id#)

</insert>

<!-- //////////////////// -->


</sqlMap>







//ConsultationAction.java

package com.test;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


import com.util.dao.*;


import java.sql.SQLException;

import java.util.*;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


public class ConsultationAction extends ActionSupport

implements Preparable, ModelDriven<ConsultationDTO> {

private static final long serialVersionUID = 1L;

private ConsultationDTO dto;


@Override

public ConsultationDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new ConsultationDTO();

}

public String consultList() {

HttpServletRequest req = ServletActionContext.getRequest();

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 5;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

CommonDAO dao = CommonDAOImpl.getInstance();

//페이지 처리 전

//List<Object> arrayList = dao.getListData("consultation.lists");

//--------------------------

//페이지 처리 후

recordCount = dao.getIntValue("consultation.count");

Map<String, Object> map = new HashMap<String, Object>();

map.put("start", start);

map.put("end", end);

List<Object> arrayList = dao.getListData("consultation.pageLists", map);

//--------------------------

//---------------------------

//페이지 처리 후

com.util.MyUtil myUtil = new com.util.MyUtil();

String pageUrl = "[1][2][3][4]...";

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.action");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

return SUCCESS;

}

public String consultInsert() {

CommonDAO dao = CommonDAOImpl.getInstance();

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

//-> iBatis는 자동 실행됨

//-----------------------------

try {

dao.insertData("consultation.add", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultView() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

//----------------------------------

//답변글 읽어오는 부분 추가

Object robj = null;

ConsultationDTO newdto = (ConsultationDTO)obj;

if (newdto.getRid() != null) {

robj = dao.getReadData("consultation.searchByRid", newdto);

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

List<Object> arrayList = null;

if (newdto.getCommentCount() > 0) {

arrayList = dao.getListData("consultation.commentLists"

, dto);

}

//----------------------------------

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

req.setAttribute("rdto", robj);

req.setAttribute("commentLists", arrayList);

return SUCCESS;

}

public String consultModifyForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}


}

}

public String consultModify() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("consultation.modify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultRemoveForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

try {

dao.deleteData("consultation.remove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}

}

public String adminReplyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String adminReply() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.insertUpdateData("consultation.adminReply"

,"consultation.modifySidReply" 

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultSearch() {

HttpServletRequest req = ServletActionContext.getRequest();

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");

CommonDAO dao = CommonDAOImpl.getInstance();

Map<String, String> map = new HashMap<String, String>();

map.put("skey", skey);

map.put("svalue", svalue);

List<Object> arrayList = dao.getListData("consultation.searchLists", map);

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

return SUCCESS;

}

public String commentInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setId(id);

dto.setName(name);

dao.insertUpdateData("consultation.commentAdd"

, "consultation.commentCountIncrease"

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultMemberInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String name = (String)session.getAttribute("name");

String pw = (String)session.getAttribute("id");

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setName(name);

dto.setPw(pw);

dto.setId(id);

dao.insertData("consultation.memberAdd", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}



//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action



---------------------------------------------------------------

상담 게시판에서 회원 전용 수정, 삭제 과정 추가할 것.


//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

pageContext.setAttribute("newLineChar", "\n");

pageContext.setAttribute("tabChar", "\t");

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Java 전문 교육센터</title>


<link rel="stylesheet" type="text/css" href="common.css">

<link rel="stylesheet" type="text/css" href="table.css">


<script type="text/javascript" src="consultation.js"></script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. -->${fn:replace(fn:replace(dto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span><!-- 관리자 -->${fn:replace(fn:replace(dto.name, "<", "&lt;"), ">", "&gt;")}

<c:choose>

<c:when test="${empty dto.id}">(비회원)</c:when>

<c:otherwise>(${dto.id})</c:otherwise>

</c:choose>

</span>

<span><!-- 2010-01-01 -->${dto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(dto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3>${fn:replace(fn:replace(rdto.title, "<", "&lt;"), ">", "&gt;")}</h3>

<span>${fn:replace(fn:replace(rdto.name, "<", "&lt;"), ">", "&gt;")}</span>

<span>${rdto.wdate}</span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

${fn:replace(fn:replace( fn:replace(fn:replace(fn:replace(rdto.content, "<", "&lt;"), ">", "&gt;"), "  ", "&nbsp;"), newLineChar, "<br>"), tabChar, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")}

</td>

</tr>

</table>

</div>

</c:if>

 

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 ${dto.commentCount} 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.action" method="post" id="commentInsertForm">

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

글쓴이 '${sessionScope.name}' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<c:forEach var="cdto" items="${commentLists}">

<tr>

<td>${cdto.name}</td>

<td>${cdto.title}</td>

<td>${cdto.wdate}</td>

<td>

<c:if test="${!empty sessionScope.id && cdto.id == sessionScope.id}">

<a href="">[삭제]</a>

</c:if>

</td>

</tr>

</c:forEach>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.action?sid=${dto.sid}">[*답변글쓰기]</a>

</c:if>

 

<a href="consultList.action">[목록보기]</a>

<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<c:choose>

<c:when test="${empty sessionScope.id && empty dto.id}">

<a href="consultModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="consultRemoveForm.action?sid=${dto.sid}">[글 삭제]</a>

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == dto.id}">

<a href="consultMemberModifyForm.action?sid=${dto.sid}">[글 수정]</a>

<a href="javascript:consultMemberDelete(${dto.sid})">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

<%-- ------------------------------- --%>


</div>

</div>

</div>

</body>

</html>






//consultationStruts.xml

<?xml  version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="consultation" extends="struts-default" namespace="" >

<!-- 상담게시판 글목록 출력 -->        

<action name="consultList" 

class="com.test.ConsultationAction" 

method="consultList">

<result>/consultList.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 화면 출력 -->

<action name="consultInsertForm">

<result>/consultInsertForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글쓰기 액션 처리 -->

<action name="consultInsert"

class="com.test.ConsultationAction"

method="consultInsert">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 내용보기 액션 처리 -->

<action name="consultView"

class="com.test.ConsultationAction"

method="consultView">

<result>/consultView.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 화면 출력 --> 

<action name="consultModifyForm"

class="com.test.ConsultationAction"

method="consultModifyForm">

<result name="error">/consultPW.jsp</result>

<result name="success">/consultModifyForm.jsp</result>

</action>

<!-- 상담게시판 비회원 글 수정 액션 처리 --> 

<action name="consultModify"

class="com.test.ConsultationAction"

method="consultModify">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>


<!-- 상담게시판 비회원 글 삭제 액션 처리 --> 

<action name="consultRemoveForm"

class="com.test.ConsultationAction"

method="consultRemoveForm">

<result name="error">/consultPW.jsp</result>

<result name="success" type="redirectAction">consultList.action</result>

</action>



<!-- 상담게시판 답변글 입력 화면 출력(관리자 전용) -->

<action name="adminReplyForm"

class="com.test.ConsultationAction"

method="adminReplyForm">

<result>/adminReplyForm.jsp</result>

</action>

<!-- 상담게시판 답변글 입력 액션 처리(관리자 전용) -->

<action name="adminReply"

class="com.test.ConsultationAction"

method="adminReply">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 상담게시판 글 검색 액션 처리 -->

<action name="consultSearch" 

class="com.test.ConsultationAction" 

method="consultSearch">

<result>/consultList.jsp</result>

</action>

<!-- 댓글 입력 액션 처리 -->

<action name="commentInsert"

class="com.test.ConsultationAction"

method="commentInsert">

<result type="redirectAction">consultView.action?sid=${sid}</result>

</action>

<!-- 회원 전용 글쓰기 입력 화면 -->

<action name="consultMemberInsertForm">

<result>/consultMemberInsertForm.jsp</result>

</action>

<!-- 회원 전용 글쓰기 액션 처리 -->

<action name="consultMemberInsert"

class="com.test.ConsultationAction"

method="consultMemberInsert">

<result type="redirectAction">consultList.action</result>

</action>

<!-- 회원 전용 수정 액션 처리 -->

<action name="consultMemberModifyForm"

class="com.test.ConsultationAction"

method="consultMemberModifyForm">

<result>/consultModifyForm.jsp</result>

</action>

<!-- 회원 전용 삭제 액션 처리 -->

<action name="consultMemberDelete"

class="com.test.ConsultationAction"

method="consultMemberDelete">

<result type="redirectAction">consultList.action</result>

</action>

</package>

</struts>






//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.action?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

obj.submit();

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.jsp";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------




function memberPwFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberPwForm");


var pw = document.getElementById("pw");

var newpw = document.getElementById("newpw");

var pwMsg = document.getElementById("pwMsg");

var newpwMsg = document.getElementById("newpwMsg");

pwMsg.style.display = "none";

newpwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (newpw.value == "" || newpw.value.length > 20) {

newpwMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}



function memberModifyFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberModifyForm");


var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}





//consultationIbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE sqlMap      

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

    

<sqlMap namespace="consultation">


<typeAlias alias="cdto" type="com.test.ConsultationDTO"/>

<!-- 페이지 처리 전, 답변글 처리 전, 댓글 출력 전, 회원 전용 글쓰기 전 -->

<select id="lists" resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultation 

ORDER BY sid DESC

</select>

<insert id="add" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE)

</insert>

<select id="searchBySid" 

parameterClass="cdto"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

, rid

, commentCount

, id

FROM consultation

WHERE sid=#sid#

</select>

<select id="searchByPw"

parameterClass="cdto"

resultClass="Integer">

SELECT COUNT(sid) AS count 

FROM consultation 

WHERE sid=#sid# 

AND name=#name# 

AND pw=encrypt(#pw#, #name#)

</select>

<update id="modify"

parameterClass="cdto">

UPDATE consultation 

SET title=#title#

, content=#content#

, wdate=SYSDATE 

WHERE sid=#sid#

</update>

<delete id="remove" parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid#

</delete>

<insert id="adminReply" parameterClass="cdto">

INSERT INTO consultReply (rid, name, title, content, wdate) 

VALUES (consultReplySeq.nextval

, #name#

, #title#

, #content#

, SYSDATE)

</insert>

<update id="modifySidReply" parameterClass="cdto">

UPDATE consultation 

SET rid=consultReplySeq.currval 

WHERE sid=#sid#

</update>

<!-- 데이터가 아니라 문장의 일부인 경우는 $skey$ 형태로 표기할 것 -->

<select id="searchLists" 

parameterClass="java.util.Map"

resultClass="cdto">

SELECT sid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

, rid

, commentCount

, id

FROM consultation 

WHERE LOWER($skey$) LIKE '%%'||LOWER(#svalue#)||'%%' 

ORDER BY sid DESC

</select>

<!-- ////////////////////////// -->

<!-- 페이지 처리 후 -->

<select id="pageLists"

parameterClass="java.util.Map"

resultClass="cdto">

<![CDATA[

SELECT * 

FROM pageListView 

WHERE rnum>=#start# AND rnum<=#end#

]]>

</select>

<select id="count"

resultClass="Integer">

SELECT COUNT(*) AS count 

FROM consultation

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 답변글 읽어오는 전용 쿼리 추가 -->

<select id="searchByRid"

parameterClass="cdto"

resultClass="cdto">

SELECT rid, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content 

FROM consultReply 

WHERE rid=#rid#

</select>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 입력용 쿼리 -->

<insert id="commentAdd"

parameterClass="cdto">

INSERT INTO consultComment (cid, id, name, title, wdate, sid) 

VALUES (consultCommentSeq.nextval

, #id#

, #name#

, #title#

, SYSDATE

, #sid#)

</insert>

<update id="commentCountIncrease"

parameterClass="cdto">

UPDATE consultation 

SET commentCount = commentCount + 1 

WHERE sid=#sid#

</update>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 댓글 목록 읽어오는 쿼리 -->

<select id="commentLists"

parameterClass="cdto"

resultClass="cdto">

SELECT cid, id, name, title

, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate 

FROM consultComment 

WHERE sid=#sid# 

ORDER BY cid ASC

</select>

<!-- //////////////////// -->



<!-- //////////////////// -->

<!-- 회원 전용 글쓰기 쿼리 --> 

<insert id="memberAdd" parameterClass="cdto">

INSERT INTO consultation (sid, name, pw, title, content, wdate, id) 

VALUES (consultationSeq.nextVal

,#name#

,encrypt(#pw#, #name#)

,#title#

,#content#

,SYSDATE

,#id#)

</insert>

<!-- //////////////////// -->

<!-- //////////////////// -->

<!-- 회원 전용 삭제 쿼리 -->

<delete id="memberRemove"

parameterClass="cdto">

DELETE 

FROM consultation 

WHERE sid=#sid# AND id=#id#

</delete>

<!-- //////////////////// -->


</sqlMap>







//ConsultationAction.java

package com.test;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


import com.util.dao.*;


import java.sql.SQLException;

import java.util.*;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;


public class ConsultationAction extends ActionSupport

implements Preparable, ModelDriven<ConsultationDTO> {

private static final long serialVersionUID = 1L;

private ConsultationDTO dto;


@Override

public ConsultationDTO getModel() {

return dto;

}


@Override

public void prepare() throws Exception {

dto = new ConsultationDTO();

}

public String consultList() {

HttpServletRequest req = ServletActionContext.getRequest();

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 5;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

CommonDAO dao = CommonDAOImpl.getInstance();

//페이지 처리 전

//List<Object> arrayList = dao.getListData("consultation.lists");

//--------------------------

//페이지 처리 후

recordCount = dao.getIntValue("consultation.count");

Map<String, Object> map = new HashMap<String, Object>();

map.put("start", start);

map.put("end", end);

List<Object> arrayList = dao.getListData("consultation.pageLists", map);

//--------------------------

//---------------------------

//페이지 처리 후

com.util.MyUtil myUtil = new com.util.MyUtil();

String pageUrl = "[1][2][3][4]...";

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.action");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

return SUCCESS;

}

public String consultInsert() {

CommonDAO dao = CommonDAOImpl.getInstance();

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

//-> iBatis는 자동 실행됨

//-----------------------------

try {

dao.insertData("consultation.add", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultView() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

//----------------------------------

//답변글 읽어오는 부분 추가

Object robj = null;

ConsultationDTO newdto = (ConsultationDTO)obj;

if (newdto.getRid() != null) {

robj = dao.getReadData("consultation.searchByRid", newdto);

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

List<Object> arrayList = null;

if (newdto.getCommentCount() > 0) {

arrayList = dao.getListData("consultation.commentLists"

, dto);

}

//----------------------------------

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

req.setAttribute("rdto", robj);

req.setAttribute("commentLists", arrayList);

return SUCCESS;

}

public String consultModifyForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}


}

}

public String consultModify() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.updateData("consultation.modify", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultRemoveForm() {

if (dto.getName() == null && dto.getPw() == null) {

return ERROR;

} else {

CommonDAO dao = CommonDAOImpl.getInstance();

int result = dao.getIntValue("consultation.searchByPw", dto);

if (result == 0) {

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("error", "true");

return ERROR;

} else {

try {

dao.deleteData("consultation.remove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}

}

public String adminReplyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String adminReply() {

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dao.insertUpdateData("consultation.adminReply"

,"consultation.modifySidReply" 

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultSearch() {

HttpServletRequest req = ServletActionContext.getRequest();

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");

CommonDAO dao = CommonDAOImpl.getInstance();

Map<String, String> map = new HashMap<String, String>();

map.put("skey", skey);

map.put("svalue", svalue);

List<Object> arrayList = dao.getListData("consultation.searchLists", map);

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

return SUCCESS;

}

public String commentInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setId(id);

dto.setName(name);

dao.insertUpdateData("consultation.commentAdd"

, "consultation.commentCountIncrease"

, dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultMemberInsert() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String name = (String)session.getAttribute("name");

String pw = (String)session.getAttribute("id");

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setName(name);

dto.setPw(pw);

dto.setId(id);

dao.insertData("consultation.memberAdd", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

public String consultMemberModifyForm() {

CommonDAO dao = CommonDAOImpl.getInstance();

Object obj = dao.getReadData("consultation.searchBySid", dto);

HttpServletRequest req = ServletActionContext.getRequest();

req.setAttribute("dto", obj);

return SUCCESS;

}

public String consultMemberDelete() {

HttpServletRequest req = ServletActionContext.getRequest();

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

CommonDAO dao = CommonDAOImpl.getInstance();

try {

dto.setId(id);

dao.deleteData("consultation.memberRemove", dto);

} catch (SQLException e) {

System.out.println(e.toString());

}

return SUCCESS;

}

}





//요청주소

http://localhost:8090/ConsultationStruts2_20121220/consultList.action




WRITTEN BY
빨강꼬마

,