ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 게시판 만들기 - 9. 검색 리스트 구현하기
    JAVA/웹 프로그래밍 - JSP 2020. 12. 2. 18:45

    아래의 내용에 이어서 계속 구현할 것이다.

    designatedroom87.tistory.com/329

     

    게시판 만들기 - 8. 글 수정 & 글 삭제 구현하기

    로그인을 한 상태에서 게시글을 하나 선택했을 시에, 아래와 같이 나타난다. 구현할 내용은 위의 글 수정과 글 삭제 기능이다. 1. 글 수정 구현하기 /board/read.jsp에서 글 수정 버튼을 클릭을 시작

    designatedroom87.tistory.com

    list.jsp에서 한 가지 처리를 하면 된다.

    검색리스트라는 주석 있는 부분을 보자.

    "검색" 버튼을 클릭하면 조건에 일치하는 리스트를 찾아서 보여주면 된다.

    아래에서 보다시피 "검색" 버튼이 클릭되면 /board/searchList로 이동을 한다.

    이는 board.controller 패키지의 Controller의 esle if 문에서 처리를 하도록 한다.

    통상적으로 별 설명이 없으면 Controller는 board.controller패키지에 있는 컨트롤러이다.

    list.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <script>
    function dataCheck()
    {
    	if(document.getElementById("search").value == "")
    	{
    		alert("검색할 단어를 입력하세요");
    		document.getElementById("search").focus();
    		return;
    	}
    	document.form.submit();
    }
    </script>
    
    <!-- 로그인이 되지 않을 경우 페이지 이동 -->
    <c:if test="${empty sessionScope.id}">
    <jsp:forward page="/index"></jsp:forward>
    </c:if>
    <!-- ----------------- -->
    
    <div class="container">
     <h2><button class="btn" onclick="location.href='/index'"><i class="fa fa-home"></i></button>메시지 전체 리스트</h2>
    <!-- 검색리스트 -->
    <form name=form action="/board/searchList" method=post>
     	<div class="form-group">
     	
     	<select name=field>
     	<option value=title>제목</option>
     	<option value=content>내용</option>
     	<option value=write_name>작성자</option>
     	</select>
        
        <input onmouseover="this.focus()" type="text" id="search" name="search" placeholder="찾을 내용을 입력하세요">
        <button type="button" onclick=dataCheck() class="btn btn-default">검색</button>
        </div>
     </form>
    <!-- 검색리스트  -->
    
    <table class="table">
    <!-- 페이지번호 표시 -->
    <tr align="right">
    <td colspan="5">
    ${pageboard.articleCount-pageboard.firstRow+1}-${pageboard.articleCount-pageboard.endRow+1}
    [${pageboard.requestPage}/${pageboard.totalPage }]
    </td>
    </tr>
    
    <tr class="success">
    <th>번호</th><th>제목</th><th>작성자</th><th>작성일</th><th>조회수</th>
    </tr>
    <c:forEach var="board" items="${pageboard.list}">
    <tr onmouseover="this.style.backgroundColor='lightgray'" 
    	onmouseout="this.style.backgroundColor='white'"
    	onclick="location.href='/board/read?idx=${board.idx}&requestPage=${pageboard.requestPage}'">
    <td>${board.idx}</td>
    <td>
    <c:if test="${board.depth>0}">
    	<!-- &nbsp;는 하나의 공백 -->
    	<c:forEach begin="1" end="${board.depth}">&nbsp;&nbsp;&nbsp;</c:forEach><img style="width:42px; height:15px" src="/img/reply_icon.gif"/>
    	<!-- <c:forEach begin="1" end="${board.depth}">-</c:forEach>&gt; -->
    </c:if>
    ${board.title}
    
    </td>
    <td>${board.write_name}</td>
    <td>${board.write_day}</td>
    <td>${board.readcount}</td>
    </tr>
    </c:forEach>
    <!-- page list -->
    <tr>
    <td colspan=4 align=center valign="center">
    <ul class="pagination">
       
        <c:if test="${pageboard.requestPage!=1}">
        <li class="page-item"><a class="page-link" href="/board/list?requestPage=${pageboard.requestPage-1}">이전페이지</a></li>
        </c:if>
     
        <c:forEach var="i" begin="${pageboard.beginPage}" end="${pageboard.endPage}">
        <li class="page-item"><a class="page-link" href="/board/list?requestPage=${i}">${i}</a></li>
        </c:forEach>
       
        <c:if test="${pageboard.totalPage!=pageboard.requestPage}">
        <li class="page-item"><a class="page-link" href="/board/list?requestPage=${pageboard.requestPage+1}">다음페이지</a></li>
        </c:if>
        
      </ul>
    </td>
    <td>
    <button onclick="location.href='/board/insert'">글쓰기</button>
    </td>
    </tr>
    <!-- end page list -->
    </table>
    
    </div>

     

    아래는 Controller에서 searchList에 대한 내용을 처리하는 부분이다.

    검색 조건과 검색할 내용과 요청 페이지에 대한 정보를 얻어온다.

    그리고 DB에 접속해서 검색 조건과 일치하는 내용의 데이터를 얻어와야한다.

    기존의 모델인 PageBoard을 사용할 수도 있지만, field와 search를 담지 못한다.

    그렇기 때문에 새로운 모델이 하나  필요한데,

    PageBoard 클래스를 상속한 SearchPageBoard를 만들도록 한다.

    요청한 페이지에 대한 정보는 PageBoard 객체에 담을 수 있다.

    SearchPageBoard 클래스는 board.model 패키지에 정의한다.

    그리고 이 탐색한 리스트를 보여줄 웹 페이지를 하나 만든다.

    이 역할은 searchList.jsp가 한다. list.jsp와 내용은 많이 비슷하다.

    SearchPageBoard.java

    더보기
    package board.model;
    
    import java.util.List;
    
    public class SearchPageBoard extends PageBoard
    {
    	private String field;
    	private String search;
    	
    	public SearchPageBoard() { super();	}
    	
    	public SearchPageBoard(String field, String search) 
    	{
    		this.field = field;
    		this.search = search;
    	}
    	
    	public SearchPageBoard(String field, String search,
    			List<Board> list, int requestPage, int totalPage, 
    			int beginPage, int endPage, int firstRow,
    			int endRow, int articleCount, int countPerPage) 
    	{
    		super(list, requestPage, totalPage, 
    				beginPage, endPage, firstRow, endRow, articleCount, countPerPage);
    		
    		this.field = field;
    		this.search = search;
    	}
    	
    	public String getField() {return field;}
    	public void setField(String field) {this.field = field;}
    	public String getSearch() {return search;}
    	public void setSearch(String search) {this.search = search;}
    }

     

     

    BoardService.java와 BoardDAO.java 에 searchList함수를 구현한다.

    BoardService.java

    더보기
    package board.service;
    
    import board.dao.BoardDAO;
    import board.model.Board;
    import board.model.PageBoard;
    import board.model.SearchPageBoard;
    
    public class BoardService {
    	private static BoardService service = new BoardService();
    	public BoardDAO dao = BoardDAO.getInstance();
    	
    	private BoardService() {}
    	
    	public static BoardService getInstance(){return service;}
    	
    	//	글 입력
    	public int insert(String title, String content, String write_name) {
    		return dao.insert(title,content,write_name);
    	}
    	
    	//	글 입력
    	public int insert(Board board) {
    		return dao.insert(board);
    	}
    
    	public PageBoard list(int requestPage) {
    		return dao.list(requestPage);
    	}
    
    	public void incrementReadCount(int idx) {
    		dao.incrementReadCount(idx);
    	}
    
    	public Board selectById(int idx) {
    		return dao.selectById(idx);
    	}
    
    	public int replyInsert(Board board) {
    		return dao.replyInsert(board);
    	}
    
    	public int update(Board board) {
    		return dao.update(board);
    	}
    
    	public int delete(Board board) {
    		return dao.delete(board);
    	}
    
    	public SearchPageBoard searchList(SearchPageBoard searchpageboard) {
    		return dao.searchList(searchpageboard);
    	}
    }

     

    searchList함수에서 SQL문을 다시 점검해 보자. 원초적인 부분에서 조건 검색을 먼저 탐색해야 한다.

    아래의 두 SQL문 2 문장을 각 각 호출해서 그 결과를 보자.

    select * from board a where write_id like '%test%'
    order by a.groupid desc, a.depth asc, a.idx asc

    select * from board a 
    where write_id like '%test%'
    and content like '%번%'
    order by a.groupid desc, a.depth asc, a.idx asc

     

    BoardDAO.java

    더보기
    package board.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.sun.net.httpserver.Authenticator.Result;
    
    import board.model.Board;
    import board.model.PageBoard;
    import board.model.SearchPageBoard;
    
    public class BoardDAO {
    	private static BoardDAO dao = new BoardDAO();
    	
    	private BoardDAO() {}
    	public static BoardDAO getInstance() {
    		return dao;
    	}
    	
    	public Connection connect()
    	{
    		Connection conn = null;
    		
    		try {
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		conn=DriverManager.getConnection(
    		"jdbc:oracle:thin:@localhost:1521:xe","hr","1234");
    
    		if(conn==null) {System.out.println("DB접속에 실패");}
    		System.out.println("DB접속 성공");
    		
    		}catch(Exception e) {}
    		
    		return conn;
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
    	{
    		if (rs != null) 
    		{
    			try 
    			{
    				rs.close();
    			}
    			catch (SQLException e) {e.printStackTrace();}
    		}
    		this.close(conn,pstmt);
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt)
    	{
    		try {
    		pstmt.close();
    		conn.close();
    		}
    		catch (SQLException e) {e.printStackTrace();}
    	}
    	
    	//	글 입력
    	public int insert(String title, String content, String write_name) {
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		int result = 0;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			conn.setAutoCommit(false);	//	DB 트랜잭션의 시작
    			
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";
    			sql	+=	"board_groupid_seq.nextval,0,0,";
    			sql +=	"0,";
    			sql +=	"?,?,sysdate";
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, title);
    			pstmt.setString(2, content);
    			pstmt.setString(3, write_name);	//	id
    			pstmt.setString(4, write_name);	//	name
    			
    			result = pstmt.executeUpdate();
    			
    			if (result > 0) {
    				System.out.println("SQL 글 입력 성공");
    				conn.commit();
    			}else {
    				System.out.println("SQL 글 입력 실패");
    				conn.rollback();
    			}
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{	
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	
    	//	글 입력
    	public int insert(Board board) {
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		int result = 0;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			conn.setAutoCommit(false);	//	DB 트랜잭션의 시작
    			
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";
    			sql	+=	"board_groupid_seq.nextval,0,0,";
    			sql +=	"0,";
    			sql +=	"?,?,sysdate";
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setString(3, board.getWrite_name());	//	id
    			pstmt.setString(4, board.getWrite_name());	//	name
    			
    			result = pstmt.executeUpdate();
    			
    			if (result > 0) {
    				System.out.println("SQL 글 입력 성공");
    				conn.commit();
    			}else {
    				System.out.println("SQL 글 입력 실패");
    				conn.rollback();
    			}
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{	
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	public PageBoard list(int requestPage) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		List<Board> list = new ArrayList<Board>();	//	글 번호에 대한 리스트를 담는 객체
    		PageBoard pageboard = null;					//	페이지 정보와 리스트를 담는 객체
    		
    		//	페이지 관련 정보 사항
    		//int requestPage = 0;		//	요청한 페이지
    		int totalPage = 0;			//	전체 페이지
    		int beginPage = 0;			//	시작 페이지
    		int	endPage = 0;			//	마지막 페이지
    		int firstRow = 0;			//	시작 글번호
    		int endRow = 0;				//	끝 글번호
    		int articleCount = 0;		//	글의 전체 개수
    		int countPerPage = 10;		//	페이지 당 보여줄 글의 개수
    		
    		try {
    			System.out.println("-------BoardDAO-------------");
    			conn = this.connect();					//	DB접속
    			conn.setAutoCommit(false);
    			
    			//	페이지에 대한 정보
    			//	1. 전체 게시물 수 구하기(articleCount)
    			//sql = "select count(*) from board";
    			sql = "select count(*) from board where isdel=0";
    			pstmt = conn.prepareStatement(sql);
    			rs = pstmt.executeQuery();
    			if (rs.next()) {
    				articleCount = rs.getInt(1);
    			}
    			else {
    				articleCount = 0;
    			}
    			//rs.close();
    			//	2. 전체 페이지 수를 구하기(totalPage)
    			//	예를 들어 총 게시글이 71개이면, 총 페이지는 8개가 되야 한다.
    			totalPage = articleCount / countPerPage;
    			if (articleCount % countPerPage > 0)
    				totalPage += 1;
    			
    			//	3. 요청한 페이지에 대한 시작 글번호와 끝 글번호 구하기
    			firstRow = (requestPage - 1) * countPerPage + 1;
    			endRow = firstRow + countPerPage - 1; 
    			System.out.printf("firstRow : %d, endRow : %d\n",firstRow, endRow);
    			//	4. 시작 페이지 번호, 끝 페이지 번호(beginPage, endPage)
    			if (totalPage > 0) {
    				beginPage = (requestPage - 1) / countPerPage * countPerPage + 1;
    				//	beginPage = requestPage - 2;
    				endPage = beginPage + 4;	//	4는 요청 페이지를 기준으로 보여줄 페이지의 간격
    				
    				if (endPage > totalPage)	endPage = totalPage;
    			}
    			
    			//	5. 페이지에 해당하는 리스트(firstRow, endRow)
    			/*
    			 sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a order by a.groupid desc, a.depth asc, a.idx asc) where rownum <= ?";
    			sql += ") where rnum >= ?";
    			 */
    			sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a order by a.groupid desc, a.depth asc, a.idx asc) where rownum <= ? and isdel=0";
    			sql += ") where rnum >= ?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, endRow);	//	큰 수. 40이라고 가정
    			pstmt.setInt(2, firstRow);	//	작은 수. 31이라고 가정
    			rs = pstmt.executeQuery();
    			
    			//	6. DB의 리스트를 board객체에 담아 전송
    			while (rs.next()) {
    				Board board = new Board();
    				board.setIdx(rs.getInt("idx"));
    				board.setTitle(rs.getString("title"));
    				board.setContent(rs.getString("content"));
    				board.setReadcount(rs.getInt("readcount"));
    				board.setGroupid(rs.getInt("groupid"));
    				board.setDepth(rs.getInt("depth"));
    				board.setRe_order(rs.getInt("re_order"));
    				board.setIsdel(rs.getInt("isdel"));
    				board.setWrite_id(rs.getString("write_id"));
    				board.setWrite_name(rs.getString("write_name"));
    				board.setWrite_day(rs.getDate("write_day"));
    				
    				list.add(board);
    			}
    			
    			pageboard = new PageBoard(list, requestPage,totalPage,
    					beginPage, endPage, firstRow, endRow, articleCount,countPerPage
    					);
    			
    			this.close(conn, pstmt, rs);
    			conn.commit();
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();} 
    			
    			e.printStackTrace();
    		}
    		System.out.println("-----end BoardDAO-------------");
    		return pageboard;
    	}
    	public void incrementReadCount(int idx) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			sql = "update board set readcount=readcount+1 where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			pstmt.executeUpdate();
    			
    			this.close(conn, pstmt);
    		}catch(Exception e){}
    	}
    	public Board selectById(int idx) 
    	{
    		Board board = null;
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			//conn.setAutoCommit(false);
    			sql = "select * from board where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			rs = pstmt.executeQuery();
    			
    			if (rs.next())
    			{
    				board = new Board(
    						rs.getInt("idx"), 
    						rs.getString("title"), 
    						rs.getString("content"), 
    						rs.getInt("readcount"), 
    						rs.getInt("groupid"), 
    						rs.getInt("depth"), 
    						rs.getInt("re_order"), 
    						rs.getInt("isdel"), 
    						rs.getString("write_id"), 
    						rs.getString("write_name"), 
    						rs.getDate("write_day")
    						);
    			}	
    			//conn.commit();
    			this.close(conn, pstmt, rs);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return board;
    	}
    	
    	//	replyInsert함수에서 이용
    	public boolean checkParent(int idx) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			
    			//	isdel이 0이면 삭제가 되지 않았다는 의미
    			sql = "select count(*) from board where idx=? and isdel=0";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, idx);
    			rs = pstmt.executeQuery();
    			
    			if (rs.next()) 
    			{
    				result = rs.getInt(1);
    			}
    			if (result != 1)
    			{
    				//this.close(conn, pstmt, rs);
    				return false;
    			}
    			
    			this.close(conn, pstmt, rs);
    		}catch(Exception e) {}
    		
    		return true;
    	}
    	
    	//	replyInsert함수에서 이용
    	public void reply_before_update(int depth, int groupid) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		
    		try {
    			conn = this.connect();
    			
    			//	isdel이 0이면 삭제가 되지 않았다는 의미
    			sql = "update board set depth=depth+1 where groupid=? and depth>?";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, groupid);
    			pstmt.setInt(2, depth);
    			
    			pstmt.executeUpdate();
    				
    			this.close(conn, pstmt);
    		}catch(Exception e) {}
    	}
    	
    	public int replyInsert(Board board) 
    	{
    		//	댓글은 
    		//		1. 부모 글이 존재하는지 여부 확인 checkParent(board.getIdx());
    		//		2. 댓글과 상관이 있는 글에 대해 groupid, depth, [re_order]값을 변경 - reply_before_update(depth,groupid);
    		//				re_order는 잘 안 바뀐다.
    		//		3. 댓글이 등록 - insert();
    		//	위의 조건에 따라 DB에 저장한다.
    		
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);			//	반드시 필요하다.
    			
    			//	부모 글의 존재여부 확인
    			if(!checkParent(board.getIdx())) 	//	board의 idx는 부모 idx이다.
    			{	
    				conn.rollback();
    				return 0;
    			}
    			System.out.println("부모글 확인");
    			
    			//	댓글과 관련된 글에 대해 업데이트
    			reply_before_update(board.getDepth(),board.getGroupid());
    			System.out.println("관련 댓글 입력 완료");
    			
    			//	insert 작업
    			sql = "insert into board values(";
    			sql += "board_idx_seq.nextval,";
    			sql += "?,?,0,";		//	1.title, 2.content, readcount
    			sql	+=	"?,?,?,";		//	3.groupid, 4.depth, 5.re_order
    			sql +=	"0,";			//	삭제 여부
    			sql +=	"?,?,sysdate";	//	6.write_id, 7.write_name, 8.날짜
    			sql +=	")";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setInt(3, board.getGroupid());
    			pstmt.setInt(4, board.getDepth());
    			pstmt.setInt(5, board.getRe_order());
    			pstmt.setString(6, board.getWrite_id());	//	id
    			pstmt.setString(7, board.getWrite_name());	//	name
    			//pstmt.setDate(8, (java.sql.Date)board.getWrite_day());
    			
    			result = pstmt.executeUpdate();
    			
    			if (result == 0) 
    			{
    				conn.rollback();
    				return 0;
    			}
    			else {conn.commit();}
    		}
    		catch(Exception e) 
    		{
    			try {
    				conn.rollback();
    			} catch (SQLException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    		
    		return result;
    	}
    	
    	public int update(Board board) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);	//	반드시 필요하다.
    			
    			sql = "update board set title=?, content=? where idx=?";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, board.getTitle());
    			pstmt.setString(2, board.getContent());
    			pstmt.setInt(3, board.getIdx());
    			result = pstmt.executeUpdate();
    			
    			if (result == 1)	System.out.println("업데이트 성공");
    			else				System.out.println("업데이트 실패");
    			
    			conn.commit();
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	
    	public int delete(Board board) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		String sql = null;
    		int result = 0;
    		
    		try {
    			conn = this.connect();
    			conn.setAutoCommit(false);	//	반드시 필요하다.
    			
    			//	1. 해당 글에 댓글이 있는지 확인한다.
    			
    			//	DB에서 실제 데이터를 삭제하지 않고 isdel을 1로 설정한다.
    			sql = "update board set isdel=1 where idx=?";
    			
    			//	조건 리스트 검색 시 조건에 isdel=0인 조건을 만족하는 리스트를 찾아라.
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, board.getIdx());
    			result = pstmt.executeUpdate();
    			
    			if (result == 1)	System.out.println("삭제 성공");
    			else				System.out.println("삭제 실패");
    			
    			conn.commit();
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    	
    	public SearchPageBoard searchList(SearchPageBoard searchpageboard) 
    	{
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		ResultSet rs = null;
    		String sql = null;
    		List<Board> list = new ArrayList<Board>();	//	글 번호에 대한 리스트를 담는 객체
    		//	페이지 정보와 리스트를 담는 객체는 매개변수의 객체를 이용할 것이다.
    		
    		//	페이지 관련 정보 사항
    		//int requestPage = 0;		//	요청한 페이지
    		int totalPage = 0;			//	전체 페이지
    		int beginPage = 0;			//	시작 페이지
    		int	endPage = 0;			//	마지막 페이지
    		int firstRow = 0;			//	시작 글번호
    		int endRow = 0;				//	끝 글번호
    		int articleCount = 0;		//	글의 전체 개수
    		int countPerPage = 10;		//	페이지 당 보여줄 글의 개수
    		
    		try {
    			System.out.println("-------SearchBoardDAO-------------");
    			conn = this.connect();	//	DB접속
    			conn.setAutoCommit(false);
    			
    			//	페이지에 대한 정보
    			//	1. 전체 게시물 수 구하기(articleCount)
    			//sql = "select count(*) from board";
    			sql = "select count(*) from board where ";
    			sql += searchpageboard.getField();
    			sql += " like '%";
    			sql += searchpageboard.getSearch();
    			sql += "%'";
    			
    			pstmt = conn.prepareStatement(sql);
    			rs = pstmt.executeQuery();
    			if (rs.next()) {
    				articleCount = rs.getInt(1);
    			}
    			else {
    				articleCount = 0;
    			}
    			//rs.close();
    			//	2. 전체 페이지 수를 구하기(totalPage)
    			//	예를 들어 총 게시글이 71개이면, 총 페이지는 8개가 되야 한다.
    			totalPage = articleCount / countPerPage;
    			if (articleCount % countPerPage > 0)
    				totalPage += 1;
    			
    			//	3. 요청한 페이지에 대한 시작 글번호와 끝 글번호 구하기
    			firstRow = (searchpageboard.getRequestPage() - 1) * countPerPage + 1;
    			endRow = firstRow + countPerPage - 1; 
    			System.out.printf("firstRow : %d, endRow : %d\n",firstRow, endRow);
    			//	4. 시작 페이지 번호, 끝 페이지 번호(beginPage, endPage)
    			if (totalPage > 0) {
    				beginPage = (searchpageboard.getRequestPage() - 1) / countPerPage * countPerPage + 1;
    				//	beginPage = requestPage - 2;
    				endPage = beginPage + 4;	//	4는 요청 페이지를 기준으로 보여줄 페이지의 간격
    				
    				if (endPage > totalPage)	endPage = totalPage;
    			}
    			
    			//	5. 페이지에 해당하는 리스트(firstRow, endRow)
    			/*
    			 sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a order by a.groupid desc, a.depth asc, a.idx asc) where rownum <= ?";
    			sql += ") where rnum >= ?";
    			 */
    			sql = "select idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select rownum rnum, idx, title, content, readcount, groupid, depth, re_order, isdel, write_id, write_name, write_day from (";
    			sql += "select * from board a where ";
    			sql	+= searchpageboard.getField(); 
    			sql += " like '%";
    			sql += searchpageboard.getSearch(); 
    			sql += "%' order by a.groupid desc, a.depth asc, a.idx asc)"; 
    			sql += "where rownum <= ?) where rnum >= ?";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, endRow);	//	큰 수. 40이라고 가정
    			pstmt.setInt(2, firstRow);	//	작은 수. 31이라고 가정
    			rs = pstmt.executeQuery();
    			
    			//	6. DB의 리스트를 board객체에 담아 전송
    			while (rs.next()) {
    				Board board = new Board();
    				board.setIdx(rs.getInt("idx"));
    				board.setTitle(rs.getString("title"));
    				board.setContent(rs.getString("content"));
    				board.setReadcount(rs.getInt("readcount"));
    				board.setGroupid(rs.getInt("groupid"));
    				board.setDepth(rs.getInt("depth"));
    				board.setRe_order(rs.getInt("re_order"));
    				board.setIsdel(rs.getInt("isdel"));
    				board.setWrite_id(rs.getString("write_id"));
    				board.setWrite_name(rs.getString("write_name"));
    				board.setWrite_day(rs.getDate("write_day"));
    				
    				list.add(board);
    			}
    			searchpageboard.setList(list);
    			searchpageboard.setTotalPage(totalPage);
    			searchpageboard.setBeginPage(beginPage);
    			searchpageboard.setEndPage(endPage);
    			searchpageboard.setFirstRow(firstRow);
    			searchpageboard.setEndRow(endRow);
    			searchpageboard.setArticleCount(articleCount);
    			searchpageboard.setCountPerPage(countPerPage);
    			//	requestPage와 field, search는 기본정보에 저장되어 있다.그래서 저장할 필요는 없다.
    			
    			System.out.println(searchpageboard.getList().toString());
    			this.close(conn, pstmt, rs);
    			conn.commit();
    		}
    		catch(Exception e) 
    		{
    			try {conn.rollback();} 
    			catch (SQLException e1) {e1.printStackTrace();} 
    			
    			e.printStackTrace();
    		}
    		System.out.println("-----end SearchBoardDAO-------------");
    		return searchpageboard;
    	}
    }

     

     

    searchList.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <script>
    function dataCheck()
    {
    	if(document.getElementById("search").value == "")
    	{
    		alert("검색할 단어를 입력하세요");
    		document.getElementById("search").focus();
    		return;
    	}
    	document.form.submit();
    }
    </script>
    
    <!-- 로그인이 되지 않을 경우 페이지 이동 -->
    <c:if test="${empty sessionScope.id}">
    <jsp:forward page="/index"></jsp:forward>
    </c:if>
    <!-- ----------------- -->
    
    <div class="container">
     <h2><button class="btn" onclick="location.href='/index'"><i class="fa fa-home"></i></button>메시지 전체 리스트</h2>
    <!-- 검색리스트 -->
    <form name=form action="/board/searchList" method=post>
     	<div class="form-group">
     	
     	<select name=field>
     	<option value=title>제목</option>
     	<option value=content>내용</option>
     	<option value=write_name>작성자</option>
     	</select>
        
        <input onmouseover="this.focus()" type="text" id="search" name="search" placeholder="찾을 내용을 입력하세요">
        <button type="button" onclick=dataCheck() class="btn btn-default">검색</button>
        </div>
     </form>
    <!-- 검색리스트  -->
    
    <table class="table">
    <!-- 페이지번호 표시 -->
    <tr align="right">
    <td colspan="5">
    ${pageboard.articleCount-pageboard.firstRow+1}-${pageboard.articleCount-pageboard.endRow+1}
    [${pageboard.requestPage}/${pageboard.totalPage }]
    </td>
    </tr>
    
    <tr class="success">
    <th>번호</th><th>제목</th><th>작성자</th><th>작성일</th><th>조회수</th>
    </tr>
    <c:forEach var="board" items="${pageboard.list}">
    <tr onmouseover="this.style.backgroundColor='lightgray'" 
    	onmouseout="this.style.backgroundColor='white'"
    	onclick="location.href='/board/read?idx=${board.idx}&requestPage=${pageboard.requestPage}'">
    <td>${board.idx}</td>
    <td>
    <c:if test="${board.depth>0}">
    	<!-- &nbsp;는 하나의 공백 -->
    	<c:forEach begin="1" end="${board.depth}">&nbsp;&nbsp;&nbsp;</c:forEach><img style="width:42px; height:15px" src="/img/reply_icon.gif"/>
    	<!-- <c:forEach begin="1" end="${board.depth}">-</c:forEach>&gt; -->
    </c:if>
    ${board.title}
    
    </td>
    <td>${board.write_name}</td>
    <td>${board.write_day}</td>
    <td>${board.readcount}</td>
    </tr>
    </c:forEach>
    <!-- page list -->
    <tr>
    <td colspan=4 align=center valign="center">
    <ul class="pagination">
       
        <c:if test="${pageboard.requestPage!=1}">
        <li class="page-item"><a class="page-link" href="/board/searchList?requestPage=${pageboard.requestPage-1}&field=${pageboard.field}&search=${pageboard.search}">이전페이지</a></li>
        </c:if>
     
        <c:forEach var="i" begin="${pageboard.beginPage}" end="${pageboard.endPage}">
        <li class="page-item"><a class="page-link" href="/board/searchList?requestPage=${i}&field=${pageboard.field}&search=${pageboard.search}">${i}</a></li>
        </c:forEach>
       
        <c:if test="${pageboard.totalPage!=pageboard.requestPage}">
        <li class="page-item"><a class="page-link" href="/board/searchList?requestPage=${pageboard.requestPage+1}&field=${pageboard.field}&search=${pageboard.search}">다음페이지</a></li>
        </c:if>
        
      </ul>
    </td>
    <td>
    <button onclick="location.href='/board/insert'">글쓰기</button>
    </td>
    </tr>
    <!-- end page list -->
    </table>
    
    </div>

     

     

    board.controller/Controller.java

    더보기
    package board.controller;
    
    import java.io.IOException;
    import java.util.Date;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import board.model.Board;
    import board.model.PageBoard;
    import board.model.SearchPageBoard;
    import board.service.BoardService;
    
    //	member로 들어오는 모든 url에 대해서 해당 컨트로럴가 이에 대한 처리를 하겠다는 의미
    @WebServlet("/board/*")
    public class Controller extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
    	public void init(ServletConfig config) 
    			throws ServletException {}
    
    	protected void service(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    	
    		request.setCharacterEncoding("UTF-8");		//	한글 깨짐 방지
    		//ServletContext application = request.getServletContext();	//	전역 객체
    		
    		//	페이지 페이지 마다 연결 시간 설정 가능. 전역 객체이다.
    		HttpSession session = request.getSession();					 
    		
    		//	1. 페이지를 전송하기 전에 url을 분석하고 분류해서 실행
    		String url = request.getRequestURI();
    		//System.out.println("url : " +url);
    		String contextPath = request.getContextPath();
    		//System.out.println("contextPath : " +contextPath);
    		String path = url.substring(contextPath.length());
    		//System.out.println("path : " +path);
    		String lastPath = url.substring(url.lastIndexOf('/') + 1);	//	마지막 /를 기준으로 분리
    		System.out.println("subPath : " +lastPath);
    		String command = lastPath;
    		
    		//	로그인 여부를 먼저 확인
    		if (session.getAttribute("id") != null) 
    		{
    			if (command.equals("board")) 
    			{
    				request.setAttribute("page", "list.jsp");
    			}
    			else if (command.equals("list")) 
    			{
    				//	폼에서 전송된 데이터 받기 request.getParameter()
    				String requestPage_ = request.getParameter("requestPage");
    				System.out.printf("%s\n",requestPage_);
    				int requestPage = 1;
    				if (requestPage_ != null) 
    				{
    					requestPage = Integer.parseInt(requestPage_);
    				}
    	
    				//	service-dao work
    				BoardService service = BoardService.getInstance();
    				PageBoard pageboard = new PageBoard();
    				pageboard = service.list(requestPage);
    				
    				request.setAttribute("pageboard", pageboard);
    				System.out.println(pageboard.getList().toString());
    				request.setAttribute("page", "list.jsp");
    			}
    			else if (command.equals("searchList")) 
    			{
    				String field = request.getParameter("field");
    				String search = request.getParameter("search");
    				System.out.printf("%s %s\n",field,search);
    				
    				String requestPage_ = request.getParameter("requestPage");
    				System.out.printf("%s\n",requestPage_);
    				int requestPage = 1;
    				if (requestPage_ != null) 
    				{
    					requestPage = Integer.parseInt(requestPage_);
    				}
    	
    				//	service-dao work
    				BoardService service = BoardService.getInstance();
    				
    				SearchPageBoard searchpageboard = new SearchPageBoard();
    				searchpageboard.setRequestPage(requestPage);
    				searchpageboard.setField(field);
    				searchpageboard.setSearch(search);
    				
    				//searchpageboard = service.searchList(requestPage,field,search);
    				searchpageboard = service.searchList(searchpageboard);
    				
    				request.setAttribute("pageboard", searchpageboard);
    				request.setAttribute("page", "searchList.jsp");
    			}
    			//	글쓰기버튼이 눌리면
    			else if (command.equals("insert")) 
    			{
    				request.setAttribute("page", "writeForm.jsp");
    			}
    			else if (command.equals("insert.do")) 
    			{
    				String title = request.getParameter("title");
    				String content = request.getParameter("content");
    				String write_name = request.getParameter("write_name");
    				System.out.printf("%s %s %s\n",title,content,write_name);
    				
    				//	model을 적용하여 전송
    				Board board = new Board();
    				board.setTitle(title);
    				board.setContent(content);
    				board.setWrite_name(write_name);
    				//	model 적용 end
    				
    				BoardService service = BoardService.getInstance();
    				
    				//int result = service.insert(title,content,write_name);
    				int result = service.insert(board);
    				
    				if (result == 1)
    				{
    					System.out.println("글입력 성공");
    					
    					request.setAttribute("page", "success.jsp");
    				}
    				else 
    				{
    					System.out.println("글입력 실패");
    					
    					request.setAttribute("page", "fail.jsp");
    				}
    			}
    			else if (command.equals("read")) 
    			{
    				String idx_ = request.getParameter("idx");
    				String requestPage_ = request.getParameter("requestPage");
    				System.out.printf("%s %s\n",idx_,requestPage_);
    				
    				int requestPage = 1;
    				if (requestPage_ != null) 
    					requestPage = Integer.parseInt(requestPage_);
    				
    				int idx = 0;
    				if (idx_ != null) 
    				{
    					idx = Integer.parseInt(idx_);
    					
    					BoardService service = BoardService.getInstance();
    					//	조회수가 1증가하고 해당 글에 대해 view를 해주는 작업
    					service.incrementReadCount(idx);
    					Board board = service.selectById(idx);
    					
    					request.setAttribute("board",board);
    					request.setAttribute("requestPage",requestPage);
    					request.setAttribute("page", "read.jsp");
    				}
    				else{request.setAttribute("page", "read_fail.jsp");}
    			}			
    			else if (command.equals("replyForm")) 
    			{
    				request.setAttribute("page", "replyForm.jsp");
    			}
    			else if (command.equals("reply.do")) 
    			{	
    				String parent_idx = request.getParameter("parent_idx");
    				String groupid = request.getParameter("groupid");
    				String depth = request.getParameter("depth");
    				String re_order = request.getParameter("re_order");
    				String title = request.getParameter("title");
    				String content = request.getParameter("content");
    				String write_id = request.getParameter("write_id");
    				String write_name = request.getParameter("write_name");
    				String requestPage_ = request.getParameter("requestPage");
    				
    				System.out.printf("parent_idx : %s\n",parent_idx);
    				System.out.printf("groupid : %s\n",groupid);
    				System.out.printf("depth : %s\n",depth);
    				System.out.printf("re_order : %s\n",re_order);
    				System.out.printf("title : %s\n",title);
    				System.out.printf("content : %s\n",content);
    				System.out.printf("write_id : %s\n",write_id);
    				System.out.printf("write_name : %s\n",write_name);
    				System.out.printf("requestPage : %s\n",requestPage_);
    				
    				Board board = new Board();
    				board.setIdx(Integer.parseInt(parent_idx));	//	주의<DB에 입력 시, 사용 안함> 부모가 존재하는 여부 확인
    				board.setTitle(title);
    				board.setContent(content);
    				board.setGroupid(Integer.parseInt(groupid));
    				board.setDepth(Integer.parseInt(depth) + 1);		//	기존의 depth에 1을 추가
    				board.setRe_order(Integer.parseInt(re_order) + 1);	//	기존 re_order에 1을 추가	
    				board.setWrite_id(write_id);
    				board.setWrite_name(write_name);
    				board.setWrite_day(new Date());
    				
    				int requestPage = 1;
    				if (requestPage_ != null) 
    					requestPage = Integer.parseInt(requestPage_);
    				
    				BoardService service = BoardService.getInstance();
    				
    				//	댓글은 
    				//		1. 부모 글이 존재하는지 여부 확인
    				//		2. 댓글과 상관이 있는 글에 대해 groupid, depth, [re_order]값을 변경
    				//				re_order는 잘 안 바뀐다.
    				//		3. 댓글이 등록
    				//	위의 과정의 의해 처리한다.
    				
    				//	위의 과정은 DB에서 한 번에 처리를 한다.
    				int result = service.replyInsert(board);
    				//request.setAttribute("requestPage",requestPage);
    				
    				if (result > 0)		//	댓글 입력 성공
    				{
    					PageBoard pageboard = new PageBoard();
    					pageboard = service.list(requestPage);
    					request.setAttribute("pageboard", pageboard);
    					
    					request.setAttribute("page", "list.jsp");
    				}
    				else				//	댓글 입력 실패
    				{
    					request.setAttribute("page", "reply_fail.jsp");
    				}
    			}
    			else if (command.equals("update")) 
    			{
    				//	read.jsp에서 이미 데이터를 전달했다.
    				request.setAttribute("page", "updateForm.jsp");
    			}//	else if 추가
    			else if (command.equals("update.do")) 
    			{	
    				//	업데이트 관련 내용 전달받기(trim 함수를 사용하여 전달 문자 공백 제거)
    				String idx_ = request.getParameter("idx"); 
    				String requestPage_ = request.getParameter("requestPage");
    				String title = request.getParameter("title");
    				String content = request.getParameter("content").trim();
    				
    				System.out.printf("idx : %s, requestPage : %s, title : %s, content : %s\n",
    						idx_,requestPage_,title,content);
    				
    				int requestPage = Integer.parseInt(requestPage_);
    				int idx = Integer.parseInt(idx_);
    				
    				Board board = new Board();
    				board.setIdx(idx);
    				board.setTitle(title);
    				board.setContent(content);
    				
    				BoardService service = BoardService.getInstance();
    				
    				int result = service.update(board);
    				
    				request.setAttribute("requestPage",requestPage);	//	요청한 페이지를 저장
    				
    				if (result == 1)	//	업데이트 성공
    				{
    					request.setAttribute("page", "update_success.jsp");
    				}
    				else				//	업데이트 실패
    				{
    					request.setAttribute("page", "update_fail.jsp");
    				}
    			}//	else if 추가
    			else if (command.equals("delete.do")) 
    			{
    				//	데이터를 얻어온다.
    				String idx_ = request.getParameter("idx");
    				int idx = Integer.parseInt(idx_);
    				
    				System.out.printf("idx : %s\n", idx_);
    				
    				Board board = new Board();
    				board.setIdx(idx);
    				
    				BoardService service = BoardService.getInstance();
    				
    				int result = service.delete(board);
    					
    				if (result == 1)	//	삭제 성공
    				{
    					request.setAttribute("page", "delete_success.jsp");
    				}
    				else				//	삭제 실패
    				{
    					request.setAttribute("page", "delete_fail.jsp");
    				}
    			}//	else if 추가
    			else if (command.equals("test")) 
    			{
    				//	read.jsp에서 이미 데이터를 전달했다.
    				Board board1 = (Board)request.getAttribute("board1");
    				
    				System.out.printf("title : %s, content : %s\n",
    						board1.getTitle(), board1.getContent());
    				
    				request.setAttribute("page", "usebean.jsp");
    			}//	else if 추가
    			else
    			{
    				request.setAttribute("page", "list.jsp");
    			}
    		}
    		else{	request.setAttribute("page", "fail.jsp");	}
    		
    		//	2. 분류된 url을 선택하고 전송하는 작업
    		RequestDispatcher dispatcher = request.getRequestDispatcher(
    				"/WEB-INF/board/index.jsp"
    				);
    				
    		//	3. 페이지로 밀어주는 작업
    		dispatcher.forward(request, response);
    	}
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    }

     

     

     

     

    뒤이어 아래를 구현해보자.

    designatedroom87.tistory.com/332?category=901206

     

    게시판 만들기 - 10. 이미지 업로드 구현하기

    designatedroom87.tistory.com/331?category=901206 게시판 만들기 - 9. 검색 리스트 구현하기 아래의 내용에 이어서 계속 구현할 것이다. designatedroom87.tistory.com/329 게시판 만들기 - 8. 글 수정 & 글 삭..

    designatedroom87.tistory.com

     

    댓글

Designed by Tistory.