Struct1 + iBatis 게시판(2)
3. list
3-1. list.jsp 작성
① script부분
<script type="text/javascript">
function searchData() {
var f = document.searchForm;
f.action = "<%=cp%>/boardTest.do?method=list";
f.submit();
}
</script>
② body 부분
<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="${totalCount!=0 }">
${pageIndexList }
</c:if>
<c:if test="${totalCount==0 }">
등록된 게시물이 없습니다.
</c:if>
</p>
</div>
</div>
</div>
</body>
3-2. BoardAction.java 작성
① boardTest_sqlMap.xml 작성
○ resultClass : 반환값 변수형
○ parameterClass : 필요한 변수 형
○ <![CDATA[ ~~~ ]]>
- 대괄호 안에 있는 문장은 무조건 텍스트로 변경
- <를 태그와 혼동하기 때문에 사용
<?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="boardTest">
<!-- 반복적인 내용을 처리하는 방법 ① -->
<sql id="where-list">
<!-- property(searchKey)가 compareValue(name)일때 -->
<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>
<!-- 전체 데이터 갯수 -->
<!-- map에 어떤 값이 오는지에 따라서 where-list의 isEqusl문을 include에 넣어서 실행 -->
<select id="dataCount" resultClass="int" parameterClass="map">
select nvl(count(num),0) from board
<include refid="where-list"/>
</select>
<!--
<!-- 반복적인 내용을 처리하는 방법 ② -->
<select id="dataCount" resultClass="int" parameterClass="map">
select nvl(count(num),0) from board
where $searchKey$ like '%' || #searchValue# || '%'
</select>
-->
<!-- 다음 문장을 앞으로도 계속 사용할 때 다음과 같이 정의한 후 include를 이용하여 사용가능 -->
<sql id="field-list">
num,name,subject,hitCount,to_char(created,'YYYY-MM-DD') created
</sql>
<!-- 전체 데이터 -->
<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# || '%'
order by num desc) data)
<![CDATA[
where rnum>=#start# and rnum<=#end#
]]>
</select>
</sqlMap>
② list메소드(BoardAction.java)
○ dao를 실행
○ CommonDAOImpl.java에서 해당하는 메소드 실행
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"))
searchKey = URLDecoder.decode(searchKey,"UTF-8");
//map에 searchKey / searchValue값 넣어서 데이터를 보낸다 → boardTest_sqlMap.xml에서 만든 함수에서 map을 받아서 사용하기 때문
Map<String, Object> hMap = new HashMap<String, Object>();
hMap.put("searchKey", searchKey);
hMap.put("searchValue", searchValue);
//boardTest_sqlMap.xml에서 만든 함수의 id를 id에 작성
//전체 데이터 갯수
totalDataCount = dao.getIntValue("boardTest.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는 총 4개의 데이터가 들어있다
hMap.put("start", start);
hMap.put("end", 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 + param;
request.setAttribute("lists", lists);
request.setAttribute("urlArticle", urlArticle);
request.setAttribute("pageNum", currentPage);
request.setAttribute("pageIndexList", myUtil.pageIndexList(currentPage, totalPage, urlList));
request.setAttribute("totalDataCount", totalDataCount);
return mapping.findForward("list");
}
○ CommonDAOImpl.java(dao) 내용 확인
@Override
public int getIntValue(String id, Map<String, Object> map) {
try {
return ((Integer)sqlMap.queryForObject(id,map)).intValue();
} catch (Exception e) {
System.out.println(e.toString());
}
return 0;
}
@Override
public List<Object> getListData(String id, Map<String, Object> map) {
try {
return (List<Object>)sqlMap.queryForList(id,map);
} catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
○ struts-config_boardTest.xml 추가
<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>
○ 실행화면
3-3 실행흐름
struts-config_boardTest.xml → BoardAction(list메소드) → struts-config_boardTest.xml(forward name="list") → list.jsp
- 데이터 입력후 등록하기 클릭
- /boardTest.do가 오면 struts-config_boardTest.xml 이동
- boardTestForm를 가지고 BoardAction으로 이동
- BoardAction에서 list메소드 실행
- return mapping.findForward("list"); 에 의해서 "list" 포워딩(전달) → struts-config_boardTest.xml이동
- <forward name="list" path="/boardTest/list.jsp"/>에 의해서 list.jsp 실행
①
②
③
④
⑤
⑥
⑦
⑧