게시글 검색 기능 추가

[View] list.jsp 수정 (form 추가)

[경로: src/main/webapp/board/list.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 검색 form 시작 ---------------------------------------->
<div id="divFind">
    <form name="findF" id="findF" action="find.do">
        <select name="findType">
            <option value="0">::검색 유형::</option>
            <option value="1">글제목</option>
            <option value="2">작성자</option>
            <option value="3">글내용</option>
        </select>
        <input type="text" name="findKeyword" required
        placeholder="검색어를 입력하세요">
        <button class="btn">검색</button>
    </form>
</div>
cs

실행 결과: 맨 아래에 검색창 추가됨

 

 

[Controller] BoardFindAction

[경로: src/main/java/board.controller/BoardFindAction.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class BoardFindAction extends AbstractAction {
 
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //0. pageNum 파라미터값 받기
        String pageNumStr = req.getParameter("pageNum");
        if(pageNumStr==null) {
            pageNumStr="1"//default 페이지를 1페이지로 지정
        }
        int pageNum = Integer.parseInt(pageNumStr.trim());
        if(pageNum<1) {
            pageNum = 1;
        }
        //검색 유형과 검색어 받기
        String findTypeStr = req.getParameter("findType");
        String findKeyword = req.getParameter("findKeyword");
        if(findTypeStr==null || findTypeStr.trim().isEmpty()) {
            findTypeStr="0";
        }
        int findType = Integer.parseInt(findTypeStr.trim());
        if(findType==0) {
            req.setAttribute("msg""검색 유형을 선택하세요");
            req.setAttribute("loc""javascript:history.back()");
            this.setViewName("/board/message.jsp");
            this.setRedirect(false);
            return;
        }
        //BoardDAO 생성
        BoardDAO dao = new BoardDAO();
        //1. 총 게시글 수 가져오기
        int totalCount = dao.getFindTotalCount(findType, findKeyword);
        
        //2. 한 페이지당 보여줄 목록 개수 정하기 => 5개씩 보여주기
        int oneRecordPage = 5;
        
        //3. 총 페이지수 구하기
        int pageCount = (totalCount - 1)/oneRecordPage + 1;
        System.out.println("pageCount: " + pageCount);
        //4. jsp에서 페이지 네비게이션 출력 => 링크 ==> pageNum파라미터 전달
        if(pageNum > pageCount) {
            pageNum = pageCount; //마지막 페이지로 지정
        }//url pageNum을 직접 치고 들어오는 경우를 방지
        
        //5. pageNum을 이용해서 DB에서 끊어올 범위 정하기
        int end = pageNum * oneRecordPage;
        int start = end - (oneRecordPage - 1);
        //6. 게시글 목록 가져오기
        List<BoardVO> boardList2 = dao.findBoard(start, end, findType, findKeyword);
        
        //반환하는 List<BoardVO> 객체를 req에 저장
        req.setAttribute("boardAll", boardList2);
        //페이지 관련된 각각의 숫자들을 req에 저장
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("pageCount", pageCount);
        req.setAttribute("pageNum", pageNum);
        req.setAttribute("findType", findType);
        req.setAttribute("findKeyword", findKeyword);
        
        //뷰페이지 지정
        this.setViewName("find.jsp");
        //이동방식 지정
        this.setRedirect(false); //forward방식
    }
 
}
cs

 

[Model] BoardDAO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    /**총 게시글 수2*/
    public int getFindTotalCount(int findType, String findKeyword) throws SQLException {
        try {
            con = ds.getConnection();
            String sql = "";
            if(findType==1) {
                sql = "SELECT count(num) cnt FROM mvc_board WHERE title LIKE ?";
            }else if(findType==2) {
                sql = "SELECT count(num) cnt FROM mvc_board WHERE name LIKE ?";
            }else if(findType==3) {
                sql = "SELECT count(num) cnt FROM mvc_board WHERE content LIKE ?";
            }else {
                sql = "SELECT count(num) cnt FROM mvc_board WHERE 1=2";
            }
            System.out.println(sql);
            ps = con.prepareStatement(sql);
            if(findType>0 && findType<4) {
                ps.setString(1"%"+findKeyword+"%");
            }
            rs = ps.executeQuery();
            //단일행 반환
            if(rs.next()) {
                int count = rs.getInt("cnt");
                return count;
            }
            return 0;
        } finally {
            close();
        }
        
    }
    
    /**게시글 목록2*/
    public List<BoardVO> findBoard(int start, int end, int findType, String findKeyword) throws SQLException {
        try {
            con = ds.getConnection();
            StringBuffer buf = new StringBuffer(" SELECT * FROM (")
                    .append(" SELECT rownum rn, a.* FROM ")
                    .append(" (SELECT * FROM mvc_board WHERE ");
                    if(findType==1) {
                        buf.append(" title LIKE ?");
                    }else if(findType==2) {
                        buf.append(" name LIKE ?");
                    }else if(findType==3) {
                        buf.append(" content LIKE ?");
                    }else {
                        buf.append(" 1=2");
                    }
                    buf.append(" ORDER BY num DESC) a) WHERE rn BETWEEN ? AND ?");
            String sql = buf.toString();
            ps = con.prepareStatement(sql);
            if(findType<1 || findType>3) {
                ps.setInt(1, start);
                ps.setInt(2, end);
            }else {
                ps.setString(1"%"+findKeyword+"%");
                ps.setInt(2, start);
                ps.setInt(3, end);
            }    
            rs = ps.executeQuery();
            return makeList(rs);
        } finally {
            close();
        }
    }
cs

 

 

[View] find.jsp

[경로: src/main/webapp/board/find.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!-- ---------------------------------------------------- -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!-- 제어문은 core태그에 모여 있음. 숫자, 날짜 format은 ftm태그에 있음- -->
 
<!-- content -->
<div class="container">
    <h1>MVC Board-[검색어: ${findKeyword}]</h1>
    <br>
    [<a href="input.do">글쓰기</a>]
    <br><br>
    <table border="1">
        <tr>
            <th class="m1" width="10%">글번호</th>
            <th class="m1" width="40%">글제목</th>
            <th class="m1" width="20%">작성자</th>
            <th class="m1" width="20%">작성일</th>
            <th class="m1" width="10%">조회수</th>
        </tr>
        <!--  ----------------- empty: boardArr.size()==0 -->
    <c:if test="${boardAll==null || empty boardAll}">
        <tr>
            <td colspan="5">
                <b>데이터가 없습니다</b>
            </td>
        </tr>
    </c:if>
    <c:if test="${boardAll !=null && not empty boardAll}">
        <%--for(BoardVO board:boardAll){...}와 동일함 --%>
        <c:forEach var="board" items="${boardAll}">
        <tr>
            <td>${board.num}</td>
            <td>
                <a href="view.do?num=${board.num}">${board.title}</a>
                <c:if test="${board.fileName ne null}">
                    <img src="../images/attach.png" style="width:0.8em">
                </c:if>
            </td>
            <td>${board.name}</td>
            <td>
                <fmt:formatDate value="${board.wdate}" pattern="yyyy-MM-dd"/>
            </td>
            <td>${board.readnum}</td>
        </tr>
        </c:forEach>
    </c:if>            
                <!-- ---------------------- -->
        <tr>
            <td colspan="3" style="text-align:center">
                <!-- 페이지 네비게이션 -->
                <c:forEach var="i" begin="1" end="${pageCount}" step="1">
                [<a href="find.do?pageNum=${i}&findType=${findType}&findKeyword=${findKeyword}"
                <c:if test="${pageNum==i}">class='active'</c:if>> ${i} </a>]
                </c:forEach>
            </td>
            <td colspan="2" style="text-align:center">총 게시글 수
                <span style="color:red; font-weight:bold">${totalCount}</span>
            </td>
        </tr>
    </table>
    <br><br>
    <!-- 검색 form 시작 ---------------------------------------->
    <div id="divFind">
        <form name="findF" id="findF" action="find.do">
            <select name="findType">
                <option value="0">::검색 유형::</option>
                <option value="1">글제목</option>
                <option value="2">작성자</option>
                <option value="3">글내용</option>
            </select>
            <input type="text" name="findKeyword" required
            placeholder="검색어를 입력하세요">
            <button class="btn">검색</button>
        </form>
    </div>
</div>
cs

글제목(findType = 1)에 '파일'이라고 검색한 결과

url: http://localhost:9090/MyMVC/board/find.do?pageNum=1&findType=1&findKeyword=파일

 


 

+ Recent posts