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

상담 게시판  답변글 처리

- 답변글 목록 출력 및 내용 보기 페이지 작성



//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
빨강꼬마

,