[자바 JDBC 게시판] 9일차

김정현·2022년 8월 19일

JDBC게시판

목록 보기
9/9

게시물 리스트시 페이징 ,검색 기능 추가

1) 리스트시 페이징 검색 명령어 추가

public void showList(String cmd) {
	System.out.println("== 게시물 리스트 ==");
	String[] cmdBits = cmd.split(" ");	
	int page = 1;
	String searchKeyword = "";
	if (cmdBits.length >= 3) {
		page = Integer.parseInt(cmdBits[2]);
	}

	if (cmdBits.length >= 4) {
		searchKeyword = cmdBits[3];
	}

	int itemsInAPage = 3;
	List<Article> articles = 
    articleService.getForPrintArticles(page, itemsInAPage, searchKeyword);
  • 페이징과 검색어를 추가하기 위해 article list 페이지 검색어 로 명령어를 받게함

  • int page = 1 , 페이지는 1페이지부터 시작

  • 명령어로 article list 뒤 페이지명령어가 없을시 1페이지 시작

  • 명령어로 article list 페이지검색어가 없을시 searchKeyword (검색어) 의 값은 , "" 검색어가 없다는 것

  • articleService에게 page와 itemsInAPage (페이지당 보여줄 게시물 갯수), searchKeyword (검색어)를넘겨줌

2) articleService에서 페이징 번호, 시작인덱스 , 보여줄 갯수를 정의

public List<Article> getForPrintArticles(int page, int itemsInAPage, String searchKeyword) {
	int limitFrom = (page - 1) * itemsInAPage;
	int limitTake = itemsInAPage;	
	Map<String, Object> args = new HashMap<>();
	args.put("searchKeyword", searchKeyword);
	args.put("limitFrom", limitFrom);
	args.put("limitTake", limitTake);

	return articleDao.getForPrintArticles(args);
}
  • 몇페이지를 선택하는 명령어가 없을시 1페이지부터 시작이므로
  • 몇페이지를 선택하는 명령어가 없다면 limitFrom (게시물테이블에서 가져올 게시물 시작 인덱스) 는 0 이되고 보여줄 게시물 갯수를 나타내는 limitTake는 itemsInAPage 즉 10이다.
  • 몇페이지를 선택하는 명령어 있다면, 예를 들어 3페이지를 선택하는 명령어를 받았다면( 3 - 1 ) * itemsInAPage ( 10 ) 부터 limitTake( 10 )
  • 즉, 20개 부터 10개를 보여줌, 쿼리문시 LIMIT를 이용해 20개 부터 10개를 보여주게 작성할 예정
  • 검색어 , 게시물테이블에서 가져올 게시물 시작 인덱스 ,보여줄 게시물 갯수를 인자로 articleDao에게 넘겨준다.
  • 이때 DB로부터 게시물데이터를 가져오는 articleDao에 인자를 key와 value로 Map을 넘겨줌

3) 쿼리문 수정

public List<Article> getForPrintArticles(Map<String, Object> args) {
		SecSql sql = new SecSql();		
		String searchKeyword = "";

		if (args.containsKey("searchKeyword")) {
			searchKeyword = (String) args.get("searchKeyword");
		}

		int limitFrom = -1;
		int limitTake = -1;

		if (args.containsKey("limitFrom")) {
			limitFrom = (int) args.get("limitFrom");
		}

		if (args.containsKey("limitTake")) {
			limitTake = (int) args.get("limitTake");
		}

		sql.append("SELECT A.*, M.name AS extra__writer");
		sql.append("FROM article AS A");
		sql.append("INNER JOIN member AS M");
		sql.append("ON A.memberId = M.id");
		if (searchKeyword.length() > 0) {
			sql.append("WHERE A.title LIKE CONCAT('%', ? , '%')", searchKeyword);
		}
		sql.append("ORDER BY A.id DESC");

		if (limitFrom != -1) {
			sql.append("LIMIT ?, ?", limitFrom, limitTake);
		}
  • 검색어의 length()를 이용해 유무 판별, 검색어가 없다면 "" 이므로 0
  • 검색어가 있다면 sql.append("WHERE A.title LIKE CONCAT('%', ? , '%')", searchKeyword);를 쿼리문에 추가
  • LIMIT (limitFrom, limitTake) , 게시물을 limitFrom부터 limitTake갯수 만큼 게시물테이블에서 데이터를 가져옴

0개의 댓글