Spring
72일차// Tiles를 활용한 게시판만들기 _3(게시판 페이징, 검색)
aesup
2021. 4. 20. 22:22
728x90
로그인 성공시 게시판으로 이동
bbslist.do
@RequestMapping(value = "loginAf.do", method=RequestMethod.POST)
public String loginAf(MemberDto dto, HttpServletRequest req) {
MemberDto login = service.login(dto);
if(login != null && !login.getId().equals("")) {
req.getSession().setAttribute("login", login);
// req.getSession().setMaxInactiveInterval(60 * 60 * 24);
return "redirect:/bbslist.do";
}
else {
return "redirect:/login.do";
}
}

BbsController
bbslist.do
package bit.com.a.controller;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import bit.com.a.dto.BbsDto;
import bit.com.a.dto.BbsParam;
import bit.com.a.service.BbsService;
@Controller
public class BbsController {
private static Logger logger = LoggerFactory.getLogger(BbsController.class);
@Autowired
BbsService service;
@RequestMapping(value = "bbslist.do", method = RequestMethod.GET)
public String bbslist(Model model) {
model.addAttribute("doc_title", "글목록");
return "bbslist.tiles";
}
bbslist.tiles
<definition name="bbslist.tiles" template="/WEB-INF/views/layouts-tiles.jsp">
<put-attribute name="header" value="/WEB-INF/views/commons/header.jsp"/>
<put-attribute name="top_inc" value="/WEB-INF/views/commons/top_inc.jsp"/>
<put-attribute name="top_menu" value="/WEB-INF/views/commons/top_menu.jsp"/>
<put-attribute name="left_menu" value="/WEB-INF/views/bbs/left_bbsmenu.jsp"/>
<put-attribute name="main" value="/WEB-INF/views/bbs/bbslist.jsp"/>
<put-attribute name="bottom_inc" value="/WEB-INF/views/commons/bottom_inc.jsp"/>
</definition>
bbslist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 검색 -->
<div class="box_border" style="margin-top: 5px; margin-bottom: 10px">
<form action="" id="_frmFormSearch" method="get">
<table style="margin-left: auto; margin-right: auto; margin-top: 3px; margin-bottom: 3px">
<tr>
<td>검색</td>
<td style="padding-left: 5px">
<select id="_choice" name="choice">
<option value="" selected="selected">선택</option>
<option value="title">제목</option>
<option value="content">내용</option>
<option value="writer">작성자</option>
</select>
</td>
<td style="padding-left: 5px">
<input type="text" id="_searchWord" name="searchWord">
</td>
<td style="padding-left: 5px">
<span class="button blue">
<button type="button" id="btnSearch">검색</button>
</span>
</td>
</tr>
</table>
</form>
</div>
<table class="list_table" style="width: 85%" id="_list_table">
<colgroup>
<col style="width:70px">
<col style="width:auto">
<col style="width:100px">
</colgroup>
<tr>
<th>번호</th><th>제목</th><th>조회수</th><th>작성자</th>
</tr>
</table>
<br><br>
<div class="container">
<nav aria-label="Page navigation">
<ul class="pagination" id="pagination" style="justify-content:center;"></ul>
</nav>
</div>
<br><br>
검색과 페이징 처리를 위해 Controller에 필요한 메소드 작성
페이징은 Pagingnation을 사용함
jquery.twbsPagination.min.js 스크립트 파일은 header.jsp에서 호출해준다
어차피 layouts-tiles.jsp에서 호출해주기때문


검색 (id = "btnSearch")클릭시
getBbsListData(0);
getBbsListCount();
function 진행
ajax를 통해 검색 결과(choice: 검색주제(제목,내용 ,작성자), search: 검색내용)를
controller에 전송
<script>
getBbsListData(0);
getBbsListCount();
//검색
$("#btnSearch").click(function(){
getBbsListData(0);
getBbsListCount();
});
// bbslist을 취득
function getBbsListData( pNumber ) {
$.ajax({
url:"./bbslistData.do",
type:"get",
data:{ page:pNumber, choice:$("#_choice").val(), search:$("#_searchWord").val() },
success:function( list ){
// alert('success');
// alert(list);
$(".list_col").remove();
$.each(list, function (i, val) {
let app = "<tr class='list_col'>"
+ "<td>" + (i + 1) + "</td>"
+ "<td class='_hover_tr' style='text-align:left'>"
+ getArrow( val.depth ); // 댓글이미지
if(val.del == 0){ // 삭제되지 않은 글
app += "<a href='bbsdetail.do?seq=" + val.seq + "'> " + val.title + "</a>";
}else{ // 삭제된 글
app += "<font color='#ff0000'>* 이 글은 작성자에 의해서 삭제되었습니다 *</font>";
}
app += "</td>";
app += "<td>" + val.readcount + "</td>";
app += "<td>" + val.id + "</td>";
app += "</tr>";
$("#_list_table").append(app);
});
},
error:function(){
alert('error');
}
});
}
검색시 bbslistData.do로 이동
param값을받기 위해 paramDTO 생성
package bit.com.a.dto;
import java.io.Serializable;
public class BbsParam implements Serializable{
private String choice;
private String search;
private int page;
private int start;
private int end;
public BbsParam() {
}
public BbsParam(String choice, String search, int page, int start, int end) {
super();
this.choice = choice;
this.search = search;
this.page = page;
this.start = start;
this.end = end;
}
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
````
Controller
글목록,
검색후 글목록
package bit.com.a.controller;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import bit.com.a.dto.BbsDto;
import bit.com.a.dto.BbsParam;
import bit.com.a.service.BbsService;
@Controller
public class BbsController {
private static Logger logger = LoggerFactory.getLogger(BbsController.class);
@Autowired
BbsService service;
@RequestMapping(value = "bbslist.do", method = RequestMethod.GET)
public String bbslist(Model model) {
model.addAttribute("doc_title", "글목록");
return "bbslist.tiles";
}
@ResponseBody
@RequestMapping(value = "bbslistData.do", method = RequestMethod.GET)
public List<BbsDto> bbslistData(BbsParam param) {
//검색처리
String choice = param.getChoice();
String search = param.getSearch();
int page = param.getPage();
if(choice == null) {
choice = "";
}
if(search == null) {
search = "";
}
param.setChoice(choice);
param.setSearch(search);
// paging 처리
int sn = param.getPage();
int start = sn * 10 + 1; // 1 11
int end = (sn + 1) * 10; // 10 20
param.setStart(start);
param.setEnd(end);
List<BbsDto> list = service.getBbslist(param);
return list;
}
Paging
글의 총수를 취득하여 페이징을 진행해야한다.
ajax를 통해 bbslistCount.do(컨트롤러)로 가서 해당 페이지, 검색을 받아
MyBatis에서 해당 게시판의 게시말 총 갯수를 return 받는다
@ResponseBody
@RequestMapping(value = "bbslistCount.do", method = RequestMethod.GET)
public int bbslistCount(BbsParam param) {
int count = service.getBbsCount(param);
return count;
}
<!-- 글의 총수 -->
<select id="getBbsCount" parameterType="bit.com.a.dto.BbsParam"
resultType="java.lang.Integer">
SELECT NVL(COUNT(*), 0)
FROM BBS
WHERE 1=1
<if test="choice != null and choice != ''
and search != null and search != ''">
<if test="choice == 'title'">
AND TITLE LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'content'">
AND CONTENT LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'writer'">
AND ID=#{search}
</if>
</if>
</select>
// 글의 총수를 취득
function getBbsListCount() {
$.ajax({
url:"./bbslistCount.do",
type:"get",
data:{ page:0, choice:$("#_choice").val(), search:$("#_searchWord").val() },
success:function( count ){
// alert('success');
// alert(count);
loadPage(count);
},
error:function(){
alert('error');
}
});
}
// paging 처리
function loadPage( totalCount ) {
let pageSize = 10;
let nowPage = 1;
let _totalPages = totalCount / pageSize;
if(totalCount % pageSize > 0){
_totalPages++;
}
$("#pagination").twbsPagination('destroy'); // 페이지 갱신 : 페이징을 갱신해 줘야 번호가 재설정된다.
$("#pagination").twbsPagination({
// startPage: 1,
totalPages: _totalPages,
visiblePages: 10,
first:'<span sria-hidden="true">«</span>',
prev:"이전",
next:"다음",
last:'<span sria-hidden="true">»</span>',
initiateStartPageClick:false, // onPageClick 자동 실행되지 않도록 한다
onPageClick:function(event, page){
nowPage = page;
// alert('nowPage:' + page);
getBbsListData( page - 1 );
}
});
}
Mapper
Bbs.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Bbs">
<!--
<select id="bbslist" resultType="bit.com.a.dto.BbsDto">
SELECT *
FROM BBS
ORDER BY REF DESC, STEP ASC
</select>
-->
<select id="bbslist" parameterType="bit.com.a.dto.BbsParam"
resultType="bit.com.a.dto.BbsDto">
SELECT SEQ, ID, REF, STEP, DEPTH, TITLE, CONTENT, WDATE, DEL, READCOUNT
FROM (SELECT ROW_NUMBER()OVER(ORDER BY REF DESC, STEP ASC) AS RNUM,
SEQ, ID, REF, STEP, DEPTH, TITLE, CONTENT, WDATE, DEL, READCOUNT
FROM BBS
WHERE 1=1
<if test="choice != null and choice != ''
and search != null and search != ''">
<!-- AND DEL=0 -->
<if test="choice == 'title'">
AND TITLE LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'content'">
AND CONTENT LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'writer'">
AND ID=#{search}
</if>
</if>
ORDER BY REF DESC, STEP ASC)
WHERE RNUM BETWEEN ${start} AND ${end}
</select>
<!-- 글의 총수 -->
<select id="getBbsCount" parameterType="bit.com.a.dto.BbsParam"
resultType="java.lang.Integer">
SELECT NVL(COUNT(*), 0)
FROM BBS
WHERE 1=1
<if test="choice != null and choice != ''
and search != null and search != ''">
<if test="choice == 'title'">
AND TITLE LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'content'">
AND CONTENT LIKE '%'||#{search}||'%'
</if>
<if test="choice == 'writer'">
AND ID=#{search}
</if>
</if>
</select>
728x90