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 (검색어)를넘겨줌
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 )검색어 , 게시물테이블에서 가져올 게시물 시작 인덱스 ,보여줄 게시물 갯수를 인자로 articleDao에게 넘겨준다.Map을 넘겨줌 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()를 이용해 유무 판별, 검색어가 없다면 "" 이므로 0sql.append("WHERE A.title LIKE CONCAT('%', ? , '%')", searchKeyword);를 쿼리문에 추가LIMIT (limitFrom, limitTake) , 게시물을 limitFrom부터 limitTake갯수 만큼 게시물테이블에서 데이터를 가져옴