Dev/Struts

Struts1/iBatis - 게시판 만들기

창문닦이 2019. 3. 20. 19:51

초기 셋팅

1. boardTest_sqlMap.xml 생성

DAO의 역할을 하는 boardTest_sqlMap.xml 생성

여기서 나오는 namespace 속성을 사용하는 지 여부를 체크하는 조건은 sqlMapconfig.xml 환경 설정 파일에서 작성된다. useStatementNamespaces="true"

컬럼명 앞뒤에 #을 두면 물음표로 자동 인식 처리된다. 세미콜론은 쓰면 안된다.

여기에서 작성되는 SQL문이 기존에 Getter, Setter를 통해 진행하는 DAO클래스의 역할을 해준다.

<?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">


<!-- Mapper -->

<sqlMap namespace="boardTest">

<select id="maxNum" resultClass="int">

select nvl(max(num),0) from board

</select>


<!-- 게시글 입력 -->

<insert id="insertData" parameterClass="com.boardTest.BoardForm">

insert into board (num,subject,name,email,content,pwd,ipAddr,hitCount,created)

values (#num#,#subject#,#name#,#email#,#content#,#pwd#,#ipAddr#,0,sysdate)

</insert>


<!-- 반복적인 내용을 처리  -->

<sql id="where-list">

<isEqual property="searchKey" compareValue="name">

where name like '%' || #searchValue# || '%'

</isEqual>

<isEqual property="searchKey" compareValue="subject">

where subject like '%' || #searchValue# || '%'

</isEqual>

<isEqual property="searchKey" compareValue="content">

where content like '%' || #searchValue# || '%'

</isEqual>

</sql>


<!-- 컬럼명을 반복적으로 사용할 경우 생성  -->

<sql id="field-list">

num,name,subject,hitCount,to_char(created,'YYYY-MM-DD') created

</sql>


<!-- 전체 데이터 갯수 -->

<select id="dataCount" resultClass="int" parameterClass="map">

select nvl(count(num),0) from board

where $searchKey$ like '%' || #searchValue# || '%'

<!-- select nvl(count(num),0) from board

<include refid="where-list"/> -->

</select>


<!-- list 데이터 조회 -->

<select id="listData" resultClass="com.boardTest.BoardForm" parameterClass="map">

select * from (

select rownum rnum, data.* from (

select <include refid="field-list"/> from board

where $searchKey$ like '%' || #searchValue# || '%'

<!-- <include refid="where-list"/> -->

order by num desc) data)

<!-- CDATA 이안에 있는 것은 모두 텍스트로 변환 -->

<![CDATA[

where rnum>=#start# and rnum<=#end#

]]>

</select>

</sqlMap>

2. sqlMapConfig.xml 에 sqlMap 등록

<?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">

<!-- Config(환경설정파일) -->

<sqlMapConfig>

<settings

cacheModelsEnabled="false"

useStatementNamespaces="true"/>

<!-- DB연결자. JDBC등록된 내용도 있고 이 내용도 함께 존재해야함 -->

<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:@192.168.16.16:1521:TestDB"/>

<property name="JDBC.Username" value="SUZI"/>

<property name="JDBC.Password" value="A123"/>

</dataSource>

</transactionManager>

<!-- 이 sqlMap은 struts에서 struts-config_temp.xml를 만들어두고 복사해서 사용한것과 동일 -->

<sqlMap resource="com/util/sqlMap/boardTest_sqlMap.xml"/>

</sqlMapConfig>

3. 자바 패키지 생성 (Model)

4. JSP페이지 폴더 생성 (View)

5. config.xml 생성 (Controller)

Controller 의 역할을 하는 struts-config_boardTest.xml 생성

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

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

"http://struts.apache.org/dtds/struts-config_1_3.dtd">

       

<struts-config>

<form-beans>

<form-bean name="boardTestForm" type="com.boardTest.BoardForm"/>

</form-beans>

<action-mappings>

<action path="/boardTest" type="com.boardTest.BoardAction"

name="boardTestForm" scope="request" parameter="method">

<forward name="created" path="/boardTest/created.jsp"/>

<forward name="created_ok" redirect="true" path="/boardTest.do?method=list"/>

<forward name="list" path="/boardTest/list.jsp"/>

</action>

</action-mappings>

</struts-config>

6. web.xml 매핑 경로 추가

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>

/WEB-INF/struts-config.xml,

/WEB-INF/struts-config_test.xml,

/WEB-INF/struts-config_board.xml,

/WEB-INF/struts-config_boardTest.xml

</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

 <servlet-mapping>

<servlet-name>action</servlet-name>

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

</servlet-mapping>



게시판 리스트 조회, 게시판 작성 기능 구현

1. BoardAction 클래스 생성

boardDAO가 없으므로 CommonDAOImpl 객체 생성을 통해 CommonDAO 생성

전역변수로 dao 객체를 생성하게되면 오류가 발생한다.

CommonDAO dao = CommonDAOImpl.getInstance();

DB를 오픈하고 나서 메소드를 실행하면 실행은 되지만 dao를 초기화. 두번째 실행시 오류 발생함

메소드안에 그때 그때 commonDAO를 생성해야 한다.

package com.boardTest;

public class BoardAction extends DispatchAction{

//게시글 작성페이지

public ActionForward created(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

return mapping.findForward("created");

}

//게시글 작성완료시

public ActionForward created_ok(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

BoardForm f = (BoardForm)form;


//boardTest_sqlMap.xml에 있는 것을 넣어준다

int maxNum=dao.getIntValue("boardTest.maxNum");

f.setNum(maxNum+1);

f.setIpAddr(request.getRemoteAddr());


//f는 boardForm을 넘겨준다 parameterClass여기안에있는 경로

dao.insertData("boardTest.insertData", f);

dao=null;

return mapping.findForward("created_ok");

}

//게시판 리스트조회시

public ActionForward list(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

String cp = request.getContextPath();

MyUtil myUtil = new MyUtil();

int numPerPage = 10;

int totalPage = 0;

int totalDataCount = 0;

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

int currentPage = 1;

if(pageNum!=null)

currentPage = Integer.parseInt(pageNum);

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

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

if(searchValue==null){

searchKey = "subject";

searchValue = "";

}

if(request.getMethod().equalsIgnoreCase("GET")){

searchValue = URLDecoder.decode(searchValue,"UTF-8");

}

Map<String, Object> hMap = new HashMap<String, Object>();

hMap.put("searchKey",searchKey);

hMap.put("searchValue",searchValue);

totalDataCount = dao.getIntValue("boardTest.dataCount", hMap);

//boardTest_sqlMap.xml 에 있는 select문 id="dataCount"에 hmap 매개변수와 함께 전달

if(totalDataCount!=0)

totalPage = myUtil.getPageCount(numPerPage, totalDataCount);

if(currentPage>totalPage)

currentPage = totalPage;

int start = (currentPage-1)*numPerPage+1;

int end = currentPage*numPerPage;

hMap.put("start",start);

hMap.put("end", end);

//hMap에는 4개의 데이터 존재 (searchKey,searchValue,start,end)

List<Object> lists = dao.getListData("boardTest.listData", hMap);

String param = "";

String urlArticle = "";

String urlList = "";

if(!searchValue.equals("")){

searchValue = URLEncoder.encode(searchValue,"UTF-8");

param = "&searchKey=" + searchKey;

param += "&searchValue=" + searchValue;

}

urlList = cp + "/boardTest.do?method=list" + param;

urlArticle = cp + "/boardTest.do?method=article&pageNum="+ currentPage;

urlArticle += param;

request.setAttribute("lists", lists);

request.setAttribute("urlArticle", urlArticle);

request.setAttribute("pageNum", pageNum);

request.setAttribute("pageIndexList", myUtil.pageIndexList(currentPage, totalPage, urlList));

request.setAttribute("totalDataCount", totalDataCount);

request.setAttribute("totalPage", totalPage);

return mapping.findForward("list");

}

}

2. created.jsp 게시판 작성 페이지

<%@ page contentType="text/html; charset=UTF-8"%>

<%request.setCharacterEncoding("UTF-8");//한글깨짐 방지%>

<%String cp = request.getContextPath();%>

<!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=UTF-8">

<title>게 시 판</title>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/style.css" type="text/css"/>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/created.css" type="text/css"/>

<script type="text/javascript" src="<%=cp%>/boardTest/js/util.js"></script>

<script type="text/javascript">

function sendIt(){

f = document.myForm;

f.action = "<%=cp%>/boardTest.do";

f.submit();

}

</script>

</head>

<body>

<div id="bbs">

<div id="bbs_title">

게 시 판(Struts1 + iBatis)

</div>

<form action="" name="myForm" method="post">

<div id="bbsCreated">

<div class="bbsCreated_bottomLine">

<dl>

<dt>제&nbsp;&nbsp;&nbsp;&nbsp;목</dt>

<dd>

<input type="text" name="subject" size="74" maxlength="100" class="boxTF"/>

</dd>

</dl>

</div>

<div class="bbsCreated_bottomLine">

<dl>

<dt>작성자</dt>

<dd>

<input type="text" name="name" size="35" maxlength="20" class="boxTF"/>

</dd>

</dl>

</div>

<div class="bbsCreated_bottomLine">

<dl>

<dt>E-Mail</dt>

<dd>

<input type="text" name="email" size="35" maxlength="50" class="boxTF"/>

</dd>

</dl>

</div>

<div id="bbsCreated_content">

<dl>

<dt>내&nbsp;&nbsp;&nbsp;&nbsp;용</dt>

<dd>

<textarea rows="12" cols="63" name="content" class="boxTA"></textarea>

</dd>

</dl>

</div>

<div class="bbsCreated_noLine">

<dl>

<dt>패스워드</dt>

<dd>

<input type="password" name="pwd" size="35" maxlength="7" class="boxTF"/>

&nbsp;{게시물 수정 및 삭제시 필요!!!}

</dd>

</dl>

</div>

<div id="bbsCreated_footer">

<input type="hidden" name="method" value="created_ok">

<input type="button" value="등록하기" class="btn2" onclick="sendIt();"/>

<input type="reset" value="다시입력" class="btn2"

onclick="document.myForm.subject.focus();"/>

<input type="button" value="작성취소" class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=list';"/>

</div>

</div>

</form>

</div>

</body>

</html>

3. list.jsp 게시판 리스트 페이지

<%@ page contentType="text/html; charset=UTF-8"%>

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

<%request.setCharacterEncoding("UTF-8");//한글깨짐 방지%>

<%String cp = request.getContextPath();%>

<!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=UTF-8">

<title>게 시 판</title>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/style.css" type="text/css"/>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/list.css" type="text/css"/>

<script type="text/javascript">

function searchData() {

var f= document.searchForm;

f.action = "<%=cp%>/boardTest.do?method=list";

f.submit();

}

</script>

</head>

<body>

<div id="bbsList">

<div id="bbsList_title">

게 시 판(Struts1 + iBatis)

</div>

<div id="bbsList_header">

<div id="leftHeader">

<form action="" name="searchForm" method="post">

<select name="searchKey" class="selectField">

<option value="subject">제목</option>

<option value="name">이름</option>

<option value="content">내용</option>

</select>

<input type="text" name="searchValue" class="textField"/>

<input type="button" value=" 검 색 " class="btn2" onclick="searchData();"/>

</form>

</div>

<div id="rightHeader">

<input type="button" value=" 글올리기 " class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=created';"/>

</div>

</div>

<div id="bbsList_list">

<div id="title">

<dl>

<dt class="num">번호</dt>

<dt class="subject">제목</dt>

<dt class="name">작성자</dt>

<dt class="created">작성일<dt>

<dt class="hitCount">조회수</dt>

</dl>

</div>

<div id="lists">

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

<dl>

<dd class="num">${dto.num}</dd>

<dd class="subject">

<a href="${urlArticle}&num=${dto.num}">${dto.subject}</a>

</dd>

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

<dd class="created">${dto.created}</dd>

<dd class="hitCount">${dto.hitCount}</dd>

</dl>

</c:forEach>

</div>

<div id="footer">

<p>

<c:if test="${totalDataCount!=0}">

${pageIndexList}

</c:if>

<c:if test="${totalDataCount==0}">

등록된 게시물이 없습니다.

</c:if>

</p>

</div>

</div>

</div>

</body>

</html>



게시글 조회 기능 구현

게시글 조회시 ‘이전글 조회’ 버튼과 ‘다음글 조회’ 버튼을 추가하고자 함

게시글 번호를 가져와서 이전글 ASC로 정렬 후 첫번째 데이터, 다음글 DESC로 정렬 후 첫번째 데이터를 사용하면 된다.



1. boardTest_sqlMap.xml

<!-- article 데이터 조회 -->

<select id="readData" resultClass="com.boardTest.BoardForm" parameterClass="int">

select num,name,subject,email,pwd,content,ipAddr,hitCount,created

from board where num=#value#

</select>

<!-- 이전글 조회(검색을 했을 경우 searchKey, searchValue 도 파라미터로 필요로함) -->

<!-- 두 조건을 만족하면서 사용자가 준 게시글 숫자보다 크면서 오름차순으로 정렬한 하나의 값만 호출 -->

<!-- rownum은 원래 내장된 컬럼이라 테이블에 추가하지 않더라도 실행됨 -->

<select id="preReadData" resultClass="com.boardTest.BoardForm" parameterClass="map">

select data.* from (

select num,subject from board

where ($searchKey$ like '%' || #searchValue# || '%')

and (num>#num#) order by num asc) data

where rownum=1

</select>

<!-- 다음글 조회 -->

<select id="nextReadData" resultClass="com.boardTest.BoardForm" parameterClass="map">

<![CDATA[

select data.* from (

select num,subject from board

where ($searchKey$ like '%' || #searchValue# || '%')

and (num<#num#) order by num desc) data

where rownum=1

]]>

</select>

<!-- 조회수증가 -->

<update id="hitCountUpdate" parameterClass="int">

update board set hitCount=hitCount+1

where num=#num#

</update >

2. boardAction클래스에 article 메소드 추가

public ActionForward article(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

String cp = request.getContextPath();

int num = Integer.parseInt(request.getParameter("num"));

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

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

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

if(searchValue==null){

searchKey = "subject";

searchValue = "";

}

if(request.getMethod().equalsIgnoreCase("GET")){

searchValue = URLDecoder.decode(searchValue,"UTF-8");

}

//조회수 증가시 숫자 1개만 변동되므로 매개변수가 updateData(string, object)인 메소드 사용

dao.updateData("boardTest.hitCountUpdate", num);

BoardForm dto= (BoardForm)dao.getReadData("boardTest.readData", num);

if(dto==null)

return mapping.findForward("list");

int lineSu = dto.getContent().split("\n").length;

dto.setContent(dto.getContent().replaceAll("\n", "<br/>"));

//이전글 다음글

String preUrl = "";

String nextUrl = "";

Map<String, Object> hMap = new HashMap<String, Object>();

hMap.put("searchKey",searchKey);

hMap.put("searchValue",searchValue);

hMap.put("num", num);

//이전글 제목

String preSubject = "";

//데이터 읽어오기

BoardForm preDTO = (BoardForm)dao.getReadData("boardTest.preReadData",hMap);//downcast

if(preDTO!=null){

//주소

preUrl = cp + "/boardTest.do?method=article&pageNum=" + pageNum;

preUrl += "&num=" + preDTO.getNum();

//제목

preSubject = preDTO.getSubject();

}

//다음글 제목

String nextSubject = "";

//데이터 읽어오기

BoardForm nextDTO = (BoardForm)dao.getReadData("boardTest.nextReadData",hMap);//downcast

if(nextDTO!=null){

//주소

nextUrl = cp + "/boardTest.do?method=article&pageNum=" + pageNum;

nextUrl += "&num=" + nextDTO.getNum();

//제목

nextSubject = nextDTO.getSubject();

}

//페이징할때 bbsArticle_footer에 있는 버튼 중

//리스트로 다시 돌아오는 기본주소

String urlList = cp + "/boardTest.do?method=list&pageNum=" + pageNum;

if(!searchValue.equals("")){

searchValue = URLEncoder.encode(searchValue,"UTF-8");

urlList += "&searchKey=" + searchKey + "&searchValue=" + searchValue;

if(!preUrl.equals("")){

preUrl += "&searchKey=" + searchKey + "&searchValue=" + searchValue;

}

if(!nextUrl.equals("")){

nextUrl += "&searchKey=" + searchKey + "&searchValue=" + earchValue;

}

}

//수정과 삭제에서 사용할 인수

String paramArticle = "num=" + num + "&pageNum=" + pageNum;

request.setAttribute("dto", dto);

request.setAttribute("preSubject", preSubject);

request.setAttribute("preUrl", preUrl);

request.setAttribute("nextSubject",nextSubject );

request.setAttribute("nextUrl", nextUrl);

request.setAttribute("lineSu", lineSu);

request.setAttribute("paramArticle", paramArticle);

request.setAttribute("urlList", urlList);

return mapping.findForward("article");

}

3. struts-config_boardTest.xml 포워드 매핑 정보 추가

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

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

"http://struts.apache.org/dtds/struts-config_1_3.dtd">

       

<struts-config>

<form-beans>

<form-bean name="boardTestForm" type="com.boardTest.BoardForm"/>

</form-beans>

<action-mappings>

<action path="/boardTest" type="com.boardTest.BoardAction"

name="boardTestForm" scope="request" parameter="method">

<forward name="created" path="/boardTest/created.jsp"/>

<forward name="created_ok" redirect="true" path="/boardTest.do?method=list"/>

<forward name="list" path="/boardTest/list.jsp"/>

<forward name="article" path="/boardTest/article.jsp"/>

</action>

</action-mappings>

</struts-config>       

4. article.jsp 게시글 조회 페이지

<%@ page contentType="text/html; charset=UTF-8"%>

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

<%request.setCharacterEncoding("UTF-8");//한글깨짐 방지%>

<%String cp = request.getContextPath();%>

<!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=UTF-8">

<title>게 시 판</title>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/style.css" type="text/css"/>

<link rel="stylesheet" href="<%=cp%>/boardTest/css/article.css" type="text/css"/>

</head>

<body>

<div id="bbs">

<div id="bbs_title">

게 시 판(Struts1 + iBatis)

</div>

<div id="bbsArticle">

<div id="bbsArticle_header">

${dto.subject}

</div>

<div class="bbsArticle_bottomLine">

<dl>

<dt>작성자</dt>

<dd>${dto.name}</dd>

<dt>줄수</dt>

<dd>${lineSu}</dd>

</dl>

</div>

<div class="bbsArticle_bottomLine">

<dl>

<dt>등록일</dt>

<dd>${dto.created}</dd>

<dt>조회수</dt>

<dd>${dto.hitCount}</dd>

</dl>

</div>

<div id="bbsArticle_content">

<table width="600" border="0">

<tr>

<td style="padding: 20px 80px 20px 62px;" valign="top" height="200">

${dto.content}

</td>

</tr>

</table>

</div>

<div class="bbsArticle_bottomLine">

이전글:

<c:if test="${!empty preUrl }">

<a href="${preUrl}">${preSubject}</a>

</c:if>

</div>

<div class="bbsArticle_noLine">

다음글:

<c:if test="${!empty nextUrl }">

<a href="${nextUrl}">${nextSubject}</a>

</c:if>

</div>

</div>

<div class="bbsArticle_noLine" style="text-align: right;">

from : ${dto.ipAddr}

</div>


<div id="bbsArticle_footer">

<div id="leftFooter">

<input type="button" value="수정" class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=created&mode=update&${paramArticle }';"/>

<input type="button" value="삭제" class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=deleted&${paramArticle }';"/>

</div>

<div id="rightFooter">

<input type="button" value="리스트" class="btn2"

onclick="javascript:location.href='${urlList}';"/>

</div>

</div>

</div>

</body>

</html>



게시글 수정 기능 구현

created.jsp와 보여지는 모습이 동일하므로 해당 jsp를 이용하여 수정 기능 또한 구현해보자

1. boardTest_sqlMap.xml에 update문 추가

<!-- 게시글 수정 -->

<update id="updateData" parameterClass="com.boardTest.BoardForm">

update board set name=#name#,subject=#subject#,email=#email#,

content=#content#,pwd=#pwd# where num=#num#

</update>

2. BoardAction 클래스의 created메소드 수정

//게시글 작성페이지

public ActionForward created(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

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

if(mode==null){

//insert

CommonDAO dao = CommonDAOImpl.getInstance();

request.setAttribute("mode", "save");

}else{

//update

CommonDAO dao = CommonDAOImpl.getInstance();

int num = Integer.parseInt(request.getParameter("num"));

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

BoardForm dto =(BoardForm)dao.getReadData("boardTest.readData",num);

if(dto==null){

return mapping.findForward("list");

}

request.setAttribute("dto", dto);

request.setAttribute("mode", "updateok");

request.setAttribute("pageNum", pageNum);

}

return mapping.findForward("created");

}

3. BoardAction 클래스의 created_ok메소드 수정(수정완료시에도 넘어가기 때문)

//게시글 작성완료시

public ActionForward created_ok(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

BoardForm f = (BoardForm)form; //페이지에서 boardForm 데이터 넘어오는걸 downcast하여 f에 할당

String mode = request.getParameter("mode");//save, updateok

if(mode.equals("save")){

//입력

int maxNum=dao.getIntValue("boardTest.maxNum");

//boardTest_sqlMap.xml에 있는 것을 넣어준다

f.setNum(maxNum+1);

f.setIpAddr(request.getRemoteAddr());

dao.insertData("boardTest.insertData", f);

//f는 boardForm을 넘겨준다 parameterClass여기안에있는 경로

dao=null;

}else{

//수정

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

dao.updateData("boardTest.updateData", f);

//pageNum을 넘기기위해 세션 사용

HttpSession session = request.getSession();

session.setAttribute("pageNum", pageNum);

}

return mapping.findForward("created_ok");

}

4. BoardAction 클래스의 list 메소드 수정

수정시 세션에 pageNum을 세션에 올려서 전달하기 때문에 boardAction 클래스의 list메소드에서도 수정이 되어야 한다

//게시판 리스트조회시

public ActionForward list(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

String cp = request.getContextPath();

MyUtil myUtil = new MyUtil();

int numPerPage = 10;

int totalPage = 0;

int totalDataCount = 0;

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

int currentPage = 1;

//created가 아닌 update에서 진행시 getParameter로 pageNum이 안오고

//세션으로 전달되므로 세션을 생성해서 받아야함

HttpSession session = request.getSession();

if(pageNum==null){

pageNum = (String)session.getAttribute("pageNum");

}


//pageNum이 getParameter, getSession 모두 안될경우 첫 실행에 해당

if(pageNum!=null)

currentPage = Integer.parseInt(pageNum);

//소스 중략//

}

5. created.jsp에 나오는 버튼 설정 

새글 작성, 기존글 수정에 따라 버튼을 변경하여 출력하도록 수정

<div id="bbsCreated_footer">

<input type="hidden" name="method" value="created_ok">

<!-- 수정시 필요한 파라미터 num과 pageNum -->

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

<input type="hidden" name="pageNum" value="${pageNum }"/>

<!-- created와 updated메소드를 구분하기 위함 -->

<input type="hidden" name="mode" value="${mode }">


<c:if test="${mode=='save' }">

<input type="button" value="등록하기" class="btn2" onclick="sendIt();"/>

<input type="reset" value="다시입력" class="btn2"

onclick="document.myForm.subject.focus();"/>

<input type="button" value="작성취소" class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=list';"/>

</c:if>

<c:if test="${mode=='updateok' }">

<input type="button" value="수정하기" class="btn2" onclick="sendIt();"/>

<input type="button" value="수정취소" class="btn2"

onclick="javascript:location.href='<%=cp%>/boardTest.do?method=list';"/>

</c:if>

</div>







게시판 삭제 기능 구현

1. dao 작성 (boardTest_sqlMap.xml 에 sql문 추가)

<!-- 게시글 삭제 -->

<delete id="deleteData" parameterClass="int">

delete board where num = #num#

</delete>

2. 매핑정보 등록 (struts-config_boardTest.xml)

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

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

"http://struts.apache.org/dtds/struts-config_1_3.dtd">

       

<struts-config>

<form-beans>

<form-bean name="boardTestForm" type="com.boardTest.BoardForm"/>

</form-beans>

<action-mappings>

<action path="/boardTest" type="com.boardTest.BoardAction"

name="boardTestForm" scope="request" parameter="method">

<forward name="created" path="/boardTest/created.jsp"/>

<forward name="created_ok" redirect="true" path="/boardTest.do?method=list"/>

<forward name="list" path="/boardTest/list.jsp"/>

<forward name="article" path="/boardTest/article.jsp"/>

<forward name="delete_ok" redirect="true" path="/boardTest.do?method=list"/>

</action>

</action-mappings>

</struts-config>

3. BoardAction 클래스에 deleted 메소드 생성

public ActionForward deleted(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

CommonDAO dao = CommonDAOImpl.getInstance();

int num = Integer.parseInt(request.getParameter("num"));

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

//dao의 sql문 실행

dao.deleteData("boardTest.deleteData", num);

//원래 페이지로 이동을 하기 위해 pageNum 받아야함. 세션으로 받음

HttpSession session = request.getSession();

session.setAttribute("pageNum", pageNum);

return mapping.findForward("delete_ok");

}


'Dev > Struts' 카테고리의 다른 글

Struts2 세팅  (0) 2019.03.21
Struts1/iBatis - 파일 업로드 기능 구현  (0) 2019.03.21
iBatis(2.0) 및 log4j 세팅  (0) 2019.03.20
Struts1/JDBC - 게시판 만들기  (2) 2019.03.19
Struts1 세팅 및 기본 예제 & MVC 패턴  (0) 2019.03.18