스프링24_페이징

charl hi·2022년 2월 18일
0

Spring

목록 보기
25/25

페이징

PageVo

@Data
public class PageVo {

	//알고 있어야 하는 값
	private int currentPage;	//현재 페이지
	private int cntPerPage;	//페이지당 볼 수 있는 row 개수
	private int pageBtnCnt;	//한번에 보여주는 페이지버튼 개수
	private int totalRow;	//테이블의 전체 row 개수

	//위를 바탕으로 구하는 
	private int startRow;	//디비가서 조회할 rownum
	private int endRow;	//디비가서 조회할 rownum
	
	private int startPage;	//시작 페이지
	private int endPage;	//마지막 페이지
	private int lastPage;	//db의 row 기준으로 마지막 페이지는 몇페이지인지
	
	public PageVo(String currentPageStr, int cntPerPage, int pageBtnCnt, int totalRow) {
		int currentPage = Integer.parseInt(currentPageStr);
		this.currentPage = currentPage;
		this.cntPerPage = cntPerPage;
		this.pageBtnCnt = pageBtnCnt;
		this.totalRow = totalRow;
		calc(currentPage, cntPerPage, pageBtnCnt, totalRow);
	}
	
	private void calc(int currentPage, int cntPerPage, int pageBtnCnt, int totalRow) {
		//나머지 5개의 값 세팅
		this.setEndRow(this.getCurrentPage() * this.getCntPerPage());
		this.setStartRow(this.getEndRow() - this.getCntPerPage() + 1);
		
		int lastPage = this.getTotalRow() / this.getCntPerPage();
		if(this.getTotalRow() % this.getCntPerPage() > 0) {
			lastPage++;
		}
		this.setLastPage(lastPage);
		
		int endPage = this.getCurrentPage() / this.getPageBtnCnt();
		if(this.getCurrentPage() % this.getPageBtnCnt() > 0) {
			endPage++;
		}
		
		if(endPage > lastPage) {
			endPage = lastPage;
		}
		
		this.setEndPage(endPage * this.getPageBtnCnt());
		
		this.setStartPage(this.getEndPage() - this.getPageBtnCnt() + 1);
	}

}


list.jsp

<body>

	<%@ include file="/WEB-INF/views/common/header.jsp" %>
	
	<div id="div-main">
		<div style="text-align:center;">
			<h1>공지사항</h1>
		</div>
		
		<table border="1" style="margin:auto;">
			<thead>
				<tr>
					<th><input type="checkbox" id="allCheck"></th>
					<th>글번호</th>
					<th>제목</th>
					<th>작성자</th>
					<th>작성시간</th>
				</tr>
			</thead>
			<tbody>
				<c:forEach items="${list}" var="n">
					<tr>
						<td><input type="checkbox" class="checkbox-del" value="${n.no}"></td>
						<td>${n.no}</td>
						<td>${n.title}</td>
						<td>${n.userNick}</td>
						<td>${n.writeDate}</td>
					</tr>
				</c:forEach>
			</tbody>
		</table>
		
		<!-- 페이징 -->
		<br><br>
 		<c:if test="${page.startPage != 1}">
			<a href="${page.startPage - 1}">이전</a>
		</c:if>
		<c:forEach var="i" begin="${page.startPage}" end="${page.endPage}">
			<c:if test="${page.currentPage != i and i <= page.lastPage}">
				<a href="${root}/notice/list/${i}">${i}</a> &nbsp
			</c:if>
			<c:if test="${page.currentPage == i and i <= page.lastPage}">${i} &nbsp</c:if>
		</c:forEach>
		<c:if test="${page.endPage < page.lastPage}">
			<a href="${page.endPage + 1}">다음</a>
		</c:if>

		<!-- 페이지 end -->		
		
		<br><br>
		<a href="${root}/notice/write">공지 작성</a>
		<button onclick="del();">삭제하기</button>
		
		
		
	</div>
	
	<script type="text/javascript">
		//전체 선택
		//let allCheck = document.querySelector('#allCheck');
		let allCheck = document.querySelector('thead input[type=checkbox]');
		let delArr = document.getElementsByClassName('checkbox-del');
		
		allCheck.onchange = function(e){
			//console.log(e.target.checked);
			console.log(this.checked);
			if(this.checked){
				for(let i=0; i<delArr.length; i++){
					delArr[i].checked = true;
				}
			}else{
				for(let i=0; i<delArr.length; i++){
					delArr[i].checked = false;
				}
			}
		}
		
		//삭제하기
		function del() {
			//삭제할 번호(들) 가져오기
			let delArr = document.getElementsByClassName('checkbox-del');
			//가져온 번호(들)을 하나의 문자열로 합치기
			let result = "";
			
			for(let i = 0; i<delArr.length; i++){
				let t = delArr[i];
				if(t.checked){
					//children[1]가 no가 있음
					//console.log(t.parentNode.parentNode.children[1].innerText);					
					console.log(t.value);	
					result += t.value + ',';
				}
			}
			
			$.ajax({
				url : "${root}/notice/delete",
				data : {"str" : result},
				type : "post",
				success : function(data){
					console.log(data);
				}, 
				error : function(error){
					console.log(error)
				},
				complete : function(){
					//새로고침
					window.location.reload();
				}
			});
		}//del()
	</script>
</body>


notice-mapper.xml

<mapper namespace="notice">

	<insert id="insertNotice" parameterType="noticeVo">
		INSERT INTO NOTICE
		(
			 NO 
		    ,TITLE
		    ,CONTENT 
		    ,WRITER 
		)
		VALUES
		(
			 NOTICE_SEQ.NEXTVAL
			,#{title}
			,#{content}
			,#{writer}
		)
		
	</insert>
	
 
 	<select id="getNoticeList" resultType="noticeVo">
 		SELECT * FROM
 		(
	 		SELECT ROWNUM RN, T.*
	 		FROM
	 		(
		 		SELECT *
	 			FROM NOTICE N
	 			JOIN MEMBER M ON (N.WRITER = M.USER_NO)
	 			WHERE N.DEL = 'N'
	 			ORDER BY N.NO
	 		) T
 		)
 		WHERE RN BETWEEN #{startRow} AND #{endRow}
 	</select>
 	
 	<update id="deleteNotice" >
 		UPDATE NOTICE
 		SET
 		DEL = 'Y'
 		WHERE NO IN 
 		<foreach collection="array" item="n" open="(" close=")" separator=",">
 		#{n}
 		</foreach>
 		
 	</update>
 	
 	<select id="getNoticeCnt" resultType="int">
 		SELECT COUNT(NO)
 		FROM NOTICE
 		WHERE DEL = 'N'
 	
 	</select>
 		
</mapper>


NoticeController

@Controller
@RequestMapping("notice")
@Slf4j
public class NoticeController {
	
	@Autowired
	private NoticeService service;

	//공지사항 화면 보여주기
//	@GetMapping(value = "/list")
//		public String list(Model model) throws Exception {
	@GetMapping(value = {"/list/{page}", "/list"})
	public String list(Model model, @PathVariable(required=false) String page) throws Exception {
		if(page == null) page = "1";
		
		//페이징 객체 필요함
		int cntPerPage = 10; //한 페이지당 row10개씩 보여주기
		int pageBtnCnt = 5;	//한번에 보여줄 페이지버튼 개수
		int totalRow = service.getNoticeCnt();	//db에 있는 모든 row 개수
		PageVo pageVo = new PageVo(page, cntPerPage, pageBtnCnt, totalRow);
		
		//리스트 조회
		List<NoticeVo> list = service.getNoticeList(pageVo);
		model.addAttribute("list", list);
		model.addAttribute("page", pageVo);
		return "notice/list";
	}
	
	//공지사항 작성 화면 보여주기(디비가서 리스트 조회)
	@GetMapping("write")
	public String write() {
		
		return "notice/write";
	}
	
	//공지사항 작성 로직 처리
	@PostMapping("write")
	public String write(NoticeVo vo, HttpServletRequest req) throws Exception {
		System.out.println(vo);
		
//		한번에 많이 만들때 이렇게
//		for(int i=0; i<500; i++) {
//			service.write(vo);
//		}
		
		int result = service.write(vo);
		if(result>0) {
			return "redirect:/notice/list";
		}else {
			req.setAttribute("msg", "공지사항 작성 실패");
			return "error/errorPage";
		}
	}
	
	//공지사항 삭제
	@PostMapping("delete")
	@ResponseBody
	public String delete(String str) throws Exception {
		System.out.println(str);	// 삭제할 번호들: 1, 5, ...
		System.out.println(str.length()/2);	// 
		
		int result = service.deleteNotice(str);
		
		log.warn("선택한 row 개수 : {}", result);
		
		if(result == str.length()/2) {
			return "ok";
		}else {
			return "fail_" + result;
		}
		
	}	
	
}


NoticeService 인페

public interface NoticeService {

	int write(NoticeVo vo) throws Exception;

	List<NoticeVo> getNoticeList(PageVo pageVo) throws Exception;

	int deleteNotice(String str) throws Exception;

	int getNoticeCnt() throws Exception;

}


NoticeServiceImpl

@Service
public class NoticeServiceImpl implements NoticeService{

	@Autowired
	private NoticeDao dao;
	
	@Override
	public int write(NoticeVo vo) throws Exception {
		
		return dao.write(vo);
	}

	@Override
	public List<NoticeVo> getNoticeList(PageVo pageVo) throws Exception {
		return dao.getNoticeList(pageVo);
	}

	@Override
	public int deleteNotice(String str) throws Exception {
		String[] delArr = str.split(",");
		return dao.deleteNotice(delArr);
	}

	@Override
	public int getNoticeCnt() throws Exception {
		return dao.getNoticeCnt();
	}

}


NoticeDao 인페

public interface NoticeDao {

	int write(NoticeVo vo) throws Exception;

	List<NoticeVo> getNoticeList(PageVo pageVo) throws Exception;

	int deleteNotice(String[] delArr) throws Exception;

	int getNoticeCnt() throws Exception;

}


NoticeDaoImpl

@Repository
public class NoticeDaoImpl implements NoticeDao{

	@Autowired
	private SqlSession sqlSession;
	
	@Override
	public int write(NoticeVo vo) throws Exception {
		return sqlSession.insert("notice.insertNotice", vo);
	}

	@Override
	public List<NoticeVo> getNoticeList(PageVo pageVo) throws Exception {
		return sqlSession.selectList("notice.getNoticeList", pageVo);
	}

	@Override
	public int deleteNotice(String[] delArr) throws Exception {
		return sqlSession.update("notice.deleteNotice", delArr);
	}

	@Override
	public int getNoticeCnt() throws Exception {
		return sqlSession.selectOne("notice.getNoticeCnt");
	}

}

0개의 댓글