Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
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
Tags
more
Archives
Today
Total
관리 메뉴

방카@Dev

[JSP]MVC Pattern2_게시판 CRUD 기능 본문

BackEnd/JSP

[JSP]MVC Pattern2_게시판 CRUD 기능

방카킴 2024. 5. 9. 17:21

1. 게시판 리스트 띄우기

➡️ Controller : BoardFrontController 에서

else if(command.equals("/BoardList.bo")){    //catch BoardList.bo 
			   action = new BoardListAction();  //BoardListAction 객체 생성(동적바인딩)
			   try{
				   forward=action.execute(request, response);  //execute 메서드 실행
			   }catch(Exception e){
				   e.printStackTrace();
			   }

➡️ BoardListAction 인스턴스 생성 및 execute 메서드 실행

 public class BoardListAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response)
	  throws Exception{
		BoardDAO boarddao=new BoardDAO();   // DB 연결 

➡️ Model : BoardDAO 객체 생성하여 DB연결

public class BoardDAO {
	Connection con;
	PreparedStatement pstmt;
	ResultSet rs;
	
	public BoardDAO() {
		try{
			Context init = new InitialContext();
	  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/MysqlDB");
	  		con = ds.getConnection();
		}catch(Exception ex){
			System.out.println("DB 연결 실패 : " + ex);
			return;
		}
	}  

➡️ BoardListAction (계속)

List boardlist=new ArrayList();       //Board 객체를 담을 리스트 생성
		
	  	int page=1;
		int limit=10;
		
		if(request.getParameter("page")!=null){
			page=Integer.parseInt(request.getParameter("page"));  //게시판 pagination 기능
		}
		
		int listcount = boarddao.getListCount();  // 글의 개수 구하기
		boardlist = boarddao.getBoardList(page,limit); //글 목록 가져오기

➡️ BoardDAO (계속)

// 글의 개수 구하기
		public int getListCount() {
			int x = 0;

			try {
				pstmt = con.prepareStatement("select count(*) from board"); //전체 게시판 수 조회
				rs = pstmt.executeQuery();

				if (rs.next()) {
					x = rs.getInt(1);
				}
			} catch (Exception ex) {
				System.out.println("getListCount 에러: " + ex);
			} finally {
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException ex) {
					}
				if (pstmt != null)
					try {
						pstmt.close();
					} catch (SQLException ex) {
					}
			}
			return x;  //전체 게시판 수 반
		}

 ======================================
		// 글 목록보기
		public List getBoardList(int page, int limit) {
			String board_list_sql = "select * from " 
			+ "(select row_number() over() rnum, BOARD_NUM,BOARD_NAME,BOARD_SUBJECT,"
			+ "BOARD_CONTENT,BOARD_FILE,BOARD_RE_REF,BOARD_RE_LEV,"
			+ "BOARD_RE_SEQ,BOARD_READCOUNT,BOARD_DATE from "
			+ "(select * from board order by BOARD_RE_REF desc,BOARD_RE_SEQ asc) AS s)AS u " 
			+ "where rnum>=? and rnum<=?";		// 오라클->코끼리 서브쿼리 부분에 별칭 추가

			List list = new ArrayList();

			int startrow = (page - 1) * 10 + 1; // 읽기 시작할 row번호
			int endrow = startrow + limit - 1; // 읽기 마지막 row번호.
			try {
				pstmt = con.prepareStatement(board_list_sql);
				pstmt.setInt(1, startrow);
				pstmt.setInt(2, endrow);
				rs = pstmt.executeQuery();

				while (rs.next()) {
					BoardBean board = new BoardBean();  게시판 빈즈 생성
					

➡️ BoardBean 게시판 빈즈

public class BoardBean {
	private int BOARD_NUM;      글 번호
	private String BOARD_NAME;  작성자 이름
	private String BOARD_PASS;  작성자 비밀번호
	private String BOARD_SUBJECT;  글 제목
	private String BOARD_CONTENT; 글 내용
	private String BOARD_FILE;  첨부파일
	private int BOARD_RE_REF; 댓글
	private int BOARD_RE_LEV; 댓글 레벨(대댓글)
	private int BOARD_RE_SEQ; 댓글 순서
	private int BOARD_READCOUNT; 조회 수
	private Date BOARD_DATE;} 게시글 날짜
	
	@Getter @Setter

➡️ BoardDAO getBoardList(계속)

      		board.setBOARD_NUM(rs.getInt("BOARD_NUM"));                   
					board.setBOARD_NAME(rs.getString("BOARD_NAME"));
					board.setBOARD_SUBJECT(rs.getString("BOARD_SUBJECT"));
					board.setBOARD_CONTENT(rs.getString("BOARD_CONTENT"));
					board.setBOARD_FILE(rs.getString("BOARD_FILE"));
					board.setBOARD_RE_REF(rs.getInt("BOARD_RE_REF"));
					board.setBOARD_RE_LEV(rs.getInt("BOARD_RE_LEV"));
					board.setBOARD_RE_SEQ(rs.getInt("BOARD_RE_SEQ"));
					board.setBOARD_READCOUNT(rs.getInt("BOARD_READCOUNT"));
					board.setBOARD_DATE(rs.getDate("BOARD_DATE"));
					list.add(board);   // ArrayList에 게시글 추가
				}

				return list;  //리스트 반환
			} catch (Exception ex) {
				System.out.println("getBoardList 에러 : " + ex);
			} finally {
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException ex) {
					}
				if (pstmt != null)
					try {
						pstmt.close();
					} catch (SQLException ex) {
					}
			}
			return list;			// DB에 DATA 없을 시 빈 리스트 반환
		}

➡️ BoardListAction (계속)

int maxpage=(int)((double)listcount/limit+0.95); 
int startpage = (((int) ((double)page / 10 + 0.9)) - 1) * 10 + 1;
int endpage = maxpage;
   		
if (endpage>startpage+10-1) endpage=startpage+10-1;
   		
request.setAttribute("page", page);		//request 저장소에 현재 조회 페이지 저장
request.setAttribute("maxpage", maxpage); //request 저장소에 최대 페이지 저장
request.setAttribute("startpage", startpage); //request 저장소에 스타트 페이지 저장
request.setAttribute("endpage", endpage); //request 저장소에 마지막 페이지 저장
request.setAttribute("listcount",listcount); //request 저장소에 listcount 저장
request.setAttribute("boardlist", boardlist); //request 저장소에 boardlist 저장
		
ActionForward forward= new ActionForward(); 
forward.setRedirect(false);     //forward로 보내기(조회 url BoardList.bo 유지)
forward.setPath("./board/qna_board_list.jsp");  //view화면 jsp 경로 설정
return forward;

➡️ Controller : BoardFrontController (계속)

   if(forward.isRedirect()){      //BoardListAction에서 반환받은 forward는 false(forward)
			   response.sendRedirect(forward.getPath());
		   }else{
			   RequestDispatcher dispatcher=            //forward할 location 설정
				   request.getRequestDispatcher(forward.getPath());
			   dispatcher.forward(request, response);  // forward 실행
		   }

➡️ View : qna_board_list

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="net.board.db.*" %>

<%
	List boardList=(List)request.getAttribute("boardlist");
	int listcount=((Integer)request.getAttribute("listcount")).intValue();
	int nowpage=((Integer)request.getAttribute("page")).intValue();
	int maxpage=((Integer)request.getAttribute("maxpage")).intValue();
	int startpage=((Integer)request.getAttribute("startpage")).intValue();
	int endpage=((Integer)request.getAttribute("endpage")).intValue();
%>

// forward에서 request로 받아온 내용 불러오기 

<html>
<head>
	<title>MVC 게시판</title>
</head>

<body>
<!-- 게시판 리스트 -->
<table width=50% border="0" cellpadding="0" cellspacing="0">
	<tr align="center" valign="middle">
		<td colspan="4">MVC 게시판</td>
		<td align=right>
			<font size=2>글 개수 : ${listcount }</font>
		</td>
	</tr>
	
	<tr align="center" valign="middle" bordercolor="#333333">
		<td style="font-family:Tahoma;font-size:8pt;" width="8%" height="26">
			<div align="center">번호</div>
		</td>
		<td style="font-family:Tahoma;font-size:8pt;" width="50%">
			<div align="center">제목</div>
		</td>
		<td style="font-family:Tahoma;font-size:8pt;" width="14%">
			<div align="center">작성자</div>
		</td>
		<td style="font-family:Tahoma;font-size:8pt;" width="17%">
			<div align="center">날짜</div>
		</td>
		<td style="font-family:Tahoma;font-size:8pt;" width="11%">
			<div align="center">조회수</div>
		</td>
	</tr>
	
	<%
		for(int i=0;i<boardList.size();i++){
			BoardBean bl=(BoardBean)boardList.get(i);
	%>  //for문으로 게시글 작성
	<tr align="center" valign="middle" bordercolor="#333333"
		onmouseover="this.style.backgroundColor='F8F8F8'"
		onmouseout="this.style.backgroundColor=''">
		<td height="23" style="font-family:Tahoma;font-size:10pt;">
			<%=bl.getBOARD_NUM()%>
		</td>
		
		<td style="font-family:Tahoma;font-size:10pt;">
			<div align="left">
			<%if(bl.getBOARD_RE_LEV()!=0){ %>
				<%for(int a=0;a<=bl.getBOARD_RE_LEV()*2;a++){ %>
				&nbsp;
				<%} %>
				▶
			<%}else{ %>
				▶
			<%} %>
			<a href="./BoardDetailAction.bo?num=<%=bl.getBOARD_NUM()%>">  //제목선택시 하이퍼링크
				<%=bl.getBOARD_SUBJECT()%>
			</a>
			</div>
		</td>
		
		<td style="font-family:Tahoma;font-size:10pt;">
			<div align="center"><%=bl.getBOARD_NAME() %></div>
		</td>
		<td style="font-family:Tahoma;font-size:10pt;">
			<div align="center"><%=bl.getBOARD_DATE() %></div>
		</td>	
		<td style="font-family:Tahoma;font-size:10pt;">
			<div align="center"><%=bl.getBOARD_READCOUNT() %></div>
		</td>
	</tr>
	<%} %>
	<tr align=center height=20>
		<td colspan=7 style=font-family:Tahoma;font-size:10pt;>
			<%if(nowpage<=1){ %>
			[이전]&nbsp;
			<%}else{ %>
			<a href="./BoardList.bo?page=<%=nowpage-1 %>">[이전]</a>&nbsp;
			<%} %>
			
			<%for(int a=startpage;a<=endpage;a++){
				if(a==nowpage){%>
				[<%=a %>]
				<%}else{ %>
				<a href="./BoardList.bo?page=<%=a %>">[<%=a %>]</a>&nbsp;
				<%} %>
			<%} %>
			
			<%if(nowpage>=maxpage){ %>
			[다음]
			<%}else{ %>
			<a href="./BoardList.bo?page=<%=nowpage+1 %>">[다음]</a>
			<%} %>
		</td>
	</tr>
	<tr align="right">
		<td colspan="5">
	   		<a href="./BoardWrite.bo">[글쓰기]</a>
		</td>
	</tr>
</table>
</body>
</html>

2. 게시판 글쓰기

  • 게시판 리스트에서 [글쓰기]버튼 선택(URL BoardWrite.bo 하이퍼링크)

➡️ Controller : BoardFrontController에서

		   if(command.equals("/BoardWrite.bo")){
			   forward=new ActionForward();      //ActionFoward 인스턴스 생성
			   forward.setRedirect(false); //forward 실행
			   forward.setPath("./board/qna_board_write.jsp");  //forward 목적지 설정
**Controller : BoardFrontController(계속)**
		   if(forward.isRedirect()){                  //isRedirect false
			   response.sendRedirect(forward.getPath());
		   }else{
			   RequestDispatcher dispatcher=
				   request.getRequestDispatcher(forward.getPath());  
			   dispatcher.forward(request, response); //qna_board_write로 forward 실행
		   }

➡️ View : qna_board_write.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>

<html>
<head>
	<title>MVC 게시판</title>
	<script language="javascript">
	function addboard(){
		boardform.submit();  //form submit 수행
	}
	</script>
</head>
<body>
<!-- 게시판 등록 -->
<form action="./BoardAddAction.bo" method="post"    //form 실행 시 BoardAddAction.bo 
	enctype="multipart/form-data" name="boardform">
<table cellpadding="0" cellspacing="0">
	<tr align="center" valign="middle">
		<td colspan="5">MVC 게시판</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">글쓴이</div>
		</td>
		<td>
			<input name="BOARD_NAME" type="text" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">비밀번호</div>
		</td>
		<td>
			<input name="BOARD_PASS" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">제 목</div>
		</td>
		<td>
			<input name="BOARD_SUBJECT" type="text" size="50" maxlength="100" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">내 용</div>
		</td>
		<td>
			<textarea name="BOARD_CONTENT" cols="67" rows="15"></textarea>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">파일 첨부</div>
		</td>
		<td>
			<input name="BOARD_FILE" type="file"/>
		</td>
	</tr>
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">
			<a href="javascript:addboard()">[등록]</a>&nbsp;&nbsp;
			<a href="javascript:history.go(-1)">[뒤로]</a>
		</td>
	</tr>
</table>
</form>
<!-- 게시판 등록 -->
</body>
</html>

➡️ Controller : BoardFrontController (form action = ./BoardAddAction.bo)

}else if(command.equals("/BoardAddAction.bo")){
			   action  = new BoardAddAction();     //BoardAddAction 동적바인딩 
			   try {
				   forward=action.execute(request, response ); //execute 실행
			   } catch (Exception e) {
				   e.printStackTrace();
			   }

➡️ BoardAddAction 인스턴스 생성

public class BoardAddAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 throws Exception{
		BoardDAO boarddao=new BoardDAO();
	  BoardBean boarddata=new BoardBean();
	  ActionForward forward=new ActionForward();
	   	
		String realFolder="";
   	String saveFolder="boardupload";
   		
   		int fileSize=5*1024*1024;
   		
   		realFolder=request.getRealPath(saveFolder);
   		
   		boolean result=false;
   		
   		try{
   			
   			MultipartRequest multi=null;
   			multi=new MultipartRequest(request,
   					realFolder,
   					fileSize,
   					"euc-kr",
   					new DefaultFileRenamePolicy());
   			
   			boarddata.setBOARD_NAME(multi.getParameter("BOARD_NAME"));    //빈즈에 데이터 입력
   			boarddata.setBOARD_PASS(multi.getParameter("BOARD_PASS"));
	   		boarddata.setBOARD_SUBJECT(multi.getParameter("BOARD_SUBJECT"));
	   		boarddata.setBOARD_CONTENT(multi.getParameter("BOARD_CONTENT"));
	   		boarddata.setBOARD_FILE(
	   				multi.getFilesystemName((String)multi.getFileNames().nextElement()));
	   		
	   		result=boarddao.boardInsert(boarddata); //db에 생성한 게시판 글 insert 수행
	

➡️ Model : boardInsert() 메서드 실행

public boolean boardInsert(BoardBean board){
				int num =0;
				String sql="";
				
				int result=0;
				
				try{
					pstmt=con.prepareStatement("select max(board_num) from board"); 
																		//게시글 중에 가장 번호가 높은거 찾기
					rs = pstmt.executeQuery();
					
					if(rs.next())
						num =rs.getInt(1)+1;    // 가장 번호가 높은거 다음번 설정
					else
						num=1;  //rs가 없으면 번호 1 설정
					
					sql="insert into board (BOARD_NUM,BOARD_NAME,BOARD_PASS,BOARD_SUBJECT,";
					sql+="BOARD_CONTENT, BOARD_FILE, BOARD_RE_REF,"+
						"BOARD_RE_LEV,BOARD_RE_SEQ,BOARD_READCOUNT,"+
						"BOARD_DATE) values(?,?,?,?,?,?,?,?,?,?,now())";
					
					pstmt = con.prepareStatement(sql);
					pstmt.setInt(1, num);
					pstmt.setString(2, board.getBOARD_NAME());   //num = max_number+1
					pstmt.setString(3, board.getBOARD_PASS());
					pstmt.setString(4, board.getBOARD_SUBJECT());
					pstmt.setString(5, board.getBOARD_CONTENT());
					pstmt.setString(6, board.getBOARD_FILE());
					pstmt.setInt(7, num);
					pstmt.setInt(8, 0);
					pstmt.setInt(9, 0);
					pstmt.setInt(10, 0);
					
					result=pstmt.executeUpdate();
					if(result==0)return false;        //boolean 값 반환
					
					return true;          //boolean 값 반환 
				}catch(Exception ex){
					System.out.println("boardInsert 에러 : "+ex);
				}finally{
					if(rs!=null) try{rs.close();}catch(SQLException ex){}
					if(pstmt!=null) try{pstmt.close();}catch(SQLException ex){}
				}
				return false;
			}

➡️ Controller : BoardAddAction(계속)

	  	   		if(result==false){
	   			System.out.println("게시글 업로드에 실패하였습니다.");
	   			return null;
	   		}
	   		System.out.println("게시글 업로드에 성공하였습니다.");
	   		
	   		forward.setRedirect(true);                 // url 변경 
	   		forward.setPath("./BoardList.bo");         // list로 돌아가기
	   		return forward;   //forward 객체 반환 Member (redirect, ./BoardList.bo) 
	   		
  		}catch(Exception ex){
   			ex.printStackTrace();
   		}
  		return null;
	}  	
}

➡️ Controller: BoardFrontController(계속)

		   if(forward.isRedirect()){       //true 
			   response.sendRedirect(forward.getPath());    //./BoardList.bo
		   }else{
			   RequestDispatcher dispatcher=
				   request.getRequestDispatcher(forward.getPath());
			   dispatcher.forward(request, response);
		   }
	 }

➡️ Redirect(./BoardList.bo) ⇒ Controller: BoardFrontController(계속)

 }else if(command.equals("/BoardList.bo")){
			   action = new BoardListAction();  
			   try{
				   forward=action.execute(request, response);  //db에서 list 뽑아와서 request담기
			   }catch(Exception e){
				   e.printStackTrace();
			   }
		   if(forward.isRedirect()){                  //false
			   response.sendRedirect(forward.getPath());
		   }else{
			   RequestDispatcher dispatcher=
				   request.getRequestDispatcher(forward.getPath());// qna_board_list로 forward 실행
			   dispatcher.forward(request, response);
		   }
	 }

3. 게시글 상세보기

➡️qna_board_list.jsp에서 제목 선택 시 하이퍼링크 연결

(./BoardDetailAction.bo?num=<%bl.getBOARD_NUM()%>)

<td style="font-family:Tahoma;font-size:10pt;">
			<div align="left">
			<%if(bl.getBOARD_RE_LEV()!=0){ %>
				<%for(int a=0;a<=bl.getBOARD_RE_LEV()*2;a++){ %>
				&nbsp;
				<%} %>
				▶
			<%}else{ %>
				▶
			<%} %>
			<a href="./BoardDetailAction.bo?num=<%=bl.getBOARD_NUM()%>">
				<%=bl.getBOARD_SUBJECT()%>     // getString으로 BOARD_NUM Controller에 전송
			</a>
			</div>
		</td>

➡️Controller: BoardFrontController

 }else if(command.equals("/BoardDetailAction.bo")){
			   action = new BoardDetailAction();      //BoardDetailAction 인스턴스 생성			   try{
				   forward=action.execute(request, response);  //execute 실행하여 forward에 담음
			   }catch(Exception e){
				   e.printStackTrace();
			   }
		   }

➡️Controller: BoardDetailAction

 public class BoardDetailAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 throws Exception{ 
		request.setCharacterEncoding("euc-kr");
   		
		BoardDAO boarddao=new BoardDAO(); 
	  BoardBean boarddata=new BoardBean();
	   	
		int num=Integer.parseInt(request.getParameter("num"));//getString으로 받은 게시글(num)
		boarddao.setReadCountUpdate(num); //db에 조회수 업데이트
	  boarddata=boarddao.getDetail(num);  //boarddata에 상세보기할 게시글 데이터 담기

➡️Model : BoardDAO

//1. 게시글 조회수 업데이트 메서드
public void setReadCountUpdate(int num) throws Exception{
String sql="update board set BOARD_READCOUNT = "+
	"BOARD_READCOUNT+1 where BOARD_NUM = "+num;

try{
	pstmt=con.prepareStatement(sql);
	pstmt.executeUpdate();
}catch(SQLException ex){
	System.out.println("setReadCountUpdate 에러 : "+ex);
}
}

//2. 게시글 세부내역 조회
public BoardBean getDetail(int num) throws Exception{
	BoardBean board = null;
	try{
		pstmt = con.prepareStatement(
				"select * from board where BOARD_NUM = ?");  //num 게시글의 모든 내용 긁어오기
		pstmt.setInt(1, num);
		
		rs= pstmt.executeQuery();
		
		if(rs.next()){
			board = new BoardBean();    //빈즈 생성 
			board.setBOARD_NUM(rs.getInt("BOARD_NUM"));  //빈즈 데이터 넣기
			board.setBOARD_NAME(rs.getString("BOARD_NAME"));
			board.setBOARD_SUBJECT(rs.getString("BOARD_SUBJECT"));
			board.setBOARD_CONTENT(rs.getString("BOARD_CONTENT"));
			board.setBOARD_FILE(rs.getString("BOARD_FILE"));
			board.setBOARD_RE_REF(rs.getInt("BOARD_RE_REF"));
			board.setBOARD_RE_LEV(rs.getInt("BOARD_RE_LEV"));
			board.setBOARD_RE_SEQ(rs.getInt("BOARD_RE_SEQ"));
			board.setBOARD_READCOUNT(rs.getInt("BOARD_READCOUNT"));
			board.setBOARD_DATE(rs.getDate("BOARD_DATE"));
		}
		return board;  // board 빈즈 반환
	}catch(Exception ex){
		System.out.println("getDetail 에러 : " + ex);
	}finally{
		if(rs!=null)try{rs.close();}catch(SQLException ex){}
		if(pstmt !=null)try{pstmt.close();}catch(SQLException ex){}
	}
	return null;
}

➡️Controller: BoardDetailAction(계속)

	   	if(boarddata==null){
	   		System.out.println("게시글이 없습니다");
	   		return null;
	   	}
	   	System.out.println("조회완료");
	   	
	   	request.setAttribute("boarddata", boarddata);  //request 저장소에 boarddata 넣기
	   	ActionForward forward = new ActionForward();
	   	forward.setRedirect(false);
   		forward.setPath("./board/qna_board_view.jsp");
   		return forward;
	 }
}

➡️Controller: BoardFrontController(계속)

 try{
   forward=action.execute(request, response);  //execute 실행하여 forward에 담음
 }catch(Exception e){                          //현재 forward(false, qna_board_view.jsp)
   e.printStackTrace();
 }
}

➡️Controller: BoardFrontController(계속)

 if(forward.isRedirect()){    //false
   response.sendRedirect(forward.getPath());  
 }else{
   RequestDispatcher dispatcher=
	   request.getRequestDispatcher(forward.getPath());
   dispatcher.forward(request, response);   //forward 실행(request = boarddata)
                                                          
 }
}

➡️View: qna_board_view.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="net.board.db.*" %>
<%
	BoardBean board = (BoardBean)request.getAttribute("boarddata");   //빈즈 데이터 꺼내기
%>

<html>
<head>
	<title>MVC 게시판</title>
</head>

<body>
<!-- 게시판 수정 -->
<table cellpadding="0" cellspacing="0">
	<tr align="center" valign="middle">
		<td colspan="5">MVC 게시판</td>
	</tr>
	
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">제 목&nbsp;&nbsp;</div>
		</td>
		
		<td style="font-family:돋음; font-size:12">
		<%=board.getBOARD_SUBJECT()%>
		</td>
	</tr>
	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">내 용</div>
		</td>
		<td style="font-family:돋음; font-size:12">
			<table border=0 width=490 height=250 style="table-layout:fixed">
				<tr>
					<td valign=top style="font-family:돋음; font-size:12">
					<%=board.getBOARD_CONTENT() %>
					</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">첨부파일</div>
		</td>
		<td style="font-family:돋음; font-size:12">
		<%if(!(board.getBOARD_FILE()==null)){ %>
		<a href="./boardupload/<%=board.getBOARD_FILE()%>">
			<%=board.getBOARD_FILE() %>
		</a>
		<%} %>
		</td>
	</tr>
	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;"></td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	
	<tr align="center" valign="middle">
		<td colspan="5">
			<font size=2>
			<a href="./BoardReplyAction.bo?num=<%=board.getBOARD_NUM() %>">
			[답변]
			</a>&nbsp;&nbsp;
			<a href="./BoardModify.bo?num=<%=board.getBOARD_NUM() %>">
			[수정]
			</a>&nbsp;&nbsp;
			<a href="./BoardDelete.bo?num=<%=board.getBOARD_NUM() %>">
			[삭제]
			</a>&nbsp;&nbsp;
			<a href="./BoardList.bo">[목록]</a>&nbsp;&nbsp;
			</font>
		</td>
	</tr>
</table>
<!-- 게시판 수정 -->
</body>
</html>

4. 게시글 수정하기

  • qna_board_view(상세보기)에서 [수정] 선택
  • "./BoardModify.bo?num=<%=board.getBOARD_NUM() %>" getString방식 게시글번호 전송

➡️Controller: BoardFrontController

}else if(command.equals("/BoardModify.bo")){ 
		   action = new BoardModifyView();  //BoardModifyView 인스턴스 생성

➡️Controller: BoardModifyView

package net.board.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.board.db.BoardDAO;
import net.board.db.BoardBean;

public class BoardModifyView implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
		 	ActionForward forward = new ActionForward();
		 	request.setCharacterEncoding("euc-kr");
	   		
			BoardDAO boarddao=new BoardDAO();
		  BoardBean boarddata=new BoardBean();
		   	
			int num=Integer.parseInt(request.getParameter("num")); getString으로 받아온 게시글번호
		  boarddata=boarddao.getDetail(num); 

➡️Model: BoardDAO

	public BoardBean getDetail(int num) throws Exception{
				BoardBean board = null;
				try{
					pstmt = con.prepareStatement(
							"select * from board where BOARD_NUM = ?");
					pstmt.setInt(1, num);
					
					rs= pstmt.executeQuery();
					
					if(rs.next()){
						board = new BoardBean();
						board.setBOARD_NUM(rs.getInt("BOARD_NUM"));
						board.setBOARD_NAME(rs.getString("BOARD_NAME"));
						board.setBOARD_SUBJECT(rs.getString("BOARD_SUBJECT"));
						board.setBOARD_CONTENT(rs.getString("BOARD_CONTENT"));
						board.setBOARD_FILE(rs.getString("BOARD_FILE"));
						board.setBOARD_RE_REF(rs.getInt("BOARD_RE_REF"));
						board.setBOARD_RE_LEV(rs.getInt("BOARD_RE_LEV"));
						board.setBOARD_RE_SEQ(rs.getInt("BOARD_RE_SEQ"));
						board.setBOARD_READCOUNT(rs.getInt("BOARD_READCOUNT"));
						board.setBOARD_DATE(rs.getDate("BOARD_DATE"));
					}
					return board;
				}catch(Exception ex){
					System.out.println("getDetail 에러 : " + ex);
				}finally{
					if(rs!=null)try{rs.close();}catch(SQLException ex){}
					if(pstmt !=null)try{pstmt.close();}catch(SQLException ex){}
				}
				return null;
			}

➡️Controller: BoardModifyView(계속)

   	if(boarddata==null){
   		System.out.println("DB에서 데이터 추출 실패");
   		return null;
   	}
   	System.out.println("데이터를 불러왔습니다");
   	
   	request.setAttribute("boarddata", boarddata);  //request 저장소에 boarddata 담기
   	forward.setRedirect(false);                    // forward 실행
 		forward.setPath("./board/qna_board_modify.jsp");  //주소 설정
 		return forward;
}
}

➡️Controller: BoardFrontController(계속)

 try{
   forward=action.execute(request, response);  //execute 실행하여 forward에 담기
 }catch(Exception e){
   e.printStackTrace();
 }

➡️Controller: BoardFrontController(계속)

 if(forward.isRedirect()){    //false
   response.sendRedirect(forward.getPath());  
 }else{
   RequestDispatcher dispatcher=
	   request.getRequestDispatcher(forward.getPath()); //qna_board_modify.jsp 경로설정
   dispatcher.forward(request, response);   // request = boarddata 
 }
}

➡️View: qna_board_modify.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="net.board.db.*" %>
<%
	BoardBean board = (BoardBean)request.getAttribute("boarddata");  //게시글 데이터 담기
%>

<html>
<head>
	<title>MVC 게시판</title>
	<script type="text/javascript">
	function modifyboard(){
		modifyform.submit();
	}
	</script>
</head>

<body>
<!-- 게시판 수정 -->
<form action="BoardModifyAction.bo" method="post" name="modifyform">
<input type="hidden" name="BOARD_NUM" value=<%=board.getBOARD_NUM() %>>
<table cellpadding="0" cellspacing="0">
	<tr align="center" valign="middle">
		<td colspan="5">MVC 게시판</td>
	</tr>
	<tr>
		<td height="16" style="font-family:돋음; font-size:12">
			<div align="center">제 목</div>
		</td>
		<td>
			<input name="BOARD_SUBJECT" size="50" maxlength="100" 
				value="<%=board.getBOARD_SUBJECT()%>">
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">내 용</div>
		</td>
		<td>
			<textarea name="BOARD_CONTENT" cols="67" rows="15">
			<%=board.getBOARD_CONTENT() %>
			</textarea>
		</td>
	</tr>
	<%if(!(board.getBOARD_FILE()==null)){ %>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">파일 첨부</div>
		</td>
		<td>
			&nbsp;&nbsp;<%=board.getBOARD_FILE() %>
		</td>
	</tr>
	<%} %>
	<tr>
		<td height="16" style="font-family:돋음; font-size:12">
			<div align="center">비밀번호</div>
		</td>
		<td>
			<input name="BOARD_PASS" type="password">
		</td>
	</tr>
	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	
	<tr align="center" valign="middle">
		<td colspan="5">
			<font size=2>
			<a href="javascript:modifyboard()">[수정]</a>&nbsp;&nbsp;
			
			// 변경데이터 form에 담아서 BoardModifyAction로 보내기
			
			<a href="javascript:history.go(-1)">[뒤로]</a>&nbsp;&nbsp;
			</font>
		</td>
	</tr>
</table>
</form>
<!-- 게시판 수정 -->
</body>
</html>

➡️Controller: BoardFrontController(계속)

  }else if(command.equals("/BoardModifyAction.bo")){
			   action = new BoardModifyAction();  //BoardModfiyAction 인스턴스 생성
			   try{
				   forward=action.execute(request, response); //forward 반환타입 execute 메서드
			   }catch(Exception e){
				   e.printStackTrace();
			   }

➡️Controller: BoardModifyAction

package net.board.action;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.board.db.*;

 public class BoardModifyAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 	throws Exception{
		 request.setCharacterEncoding("euc-kr");
		 ActionForward forward = new ActionForward();
		 boolean result = false;
		 
		 int num=Integer.parseInt(request.getParameter("BOARD_NUM")); //수정 게시판번호 반환
		 
		 BoardDAO boarddao=new BoardDAO();
		 BoardBean boarddata=new BoardBean();
		 
		 boolean usercheck=boarddao.isBoardWriter(num, request.getParameter("BOARD_PASS"));
		 //비밀번호 검증

➡️Model: BoardDAO

			public boolean isBoardWriter(int num, String pass) {
				String board_sql="select * from board where BOARD_NUM=?";
				
				try{
					pstmt=con.prepareStatement(board_sql);
					pstmt.setInt(1, num);
					rs=pstmt.executeQuery();
					rs.next();
					
					if(pass.equals(rs.getString("BOARD_PASS"))){
						return true;  //비밀번호 검증 완료 true 반환
					}
				}catch(SQLException ex){
					System.out.println("isBoardWriter 에러 : "+ex);
				}
				return false;
			}

➡️Controller: BoardModifyAction(계속)

	 if(usercheck==false){
		   		response.setContentType("text/html;charset=euc-kr");
		   		PrintWriter out=response.getWriter();
		   		out.println("<script>");
		   		out.println("alert('비밀번호 오류.');");
		   		out.println("location.href='./BoardList.bo';");
		   		out.println("</script>");
		   		out.close();
		   		return null;
		 }
		 
		 try{
			 boarddata.setBOARD_NUM(num);  //게시글 번호
			 boarddata.setBOARD_SUBJECT(request.getParameter("BOARD_SUBJECT")); //
			 //form으로 받아온 수정 제목 변경
			 boarddata.setBOARD_CONTENT(request.getParameter("BOARD_CONTENT")); //
 			 //form으로 받아온 수정 내용 변경
			 result = boarddao.boardModify(boarddata);

➡️Model: BoardDAO(계속)

	//글 수정
			public boolean boardModify(BoardBean modifyboard) throws Exception{
				String sql="update board set BOARD_SUBJECT=?,BOARD_CONTENT=? where BOARD_NUM=?";
				
				try{
					pstmt = con.prepareStatement(sql);
					pstmt.setString(1, modifyboard.getBOARD_SUBJECT());
					pstmt.setString(2, modifyboard.getBOARD_CONTENT());
					pstmt.setInt(3, modifyboard.getBOARD_NUM());
					pstmt.executeUpdate();
					return true;
				}catch(Exception ex){
					System.out.println("boardModify 에러 : " + ex);
				}finally{
					if(rs!=null)try{rs.close();}catch(SQLException ex){}
					if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
					}
				return false;
			}

➡️Controller: BoardModifyAction(계속)

			 if(result==false){
		   		System.out.println("수정에 실패하였습니다");
		   		return null;
		   	 }
		   	 System.out.println("수정에 성공하였습니다");
		   	 
		   	 forward.setRedirect(true);
		   	 forward.setPath("./BoardDetailAction.bo?num="+boarddata.getBOARD_NUM());
		   	 return forward;
	   	 }catch(Exception ex){
	   			ex.printStackTrace();	 
		 }
		 
		 return null;
	 }
}

➡️Controller: BoardFrontController(계속)

 		 forward=action.execute(request, response); //forward 반환타입 execute 메서드
   }catch(Exception e){      //request = queryString으로 num이 들어가있음 
	   e.printStackTrace();    
 }

➡️Controller: BoardFrontController(계속)

 if(forward.isRedirect()){   //true
   response.sendRedirect(forward.getPath()); 
	    //"./BoardDetailAction.bo?num="+boarddata.getBOARD_NUM())으로 이동
 }else{
   RequestDispatcher dispatcher=
	   request.getRequestDispatcher(forward.getPath());
   dispatcher.forward(request, response);
 }
}

➡️Controller: BoardFrontController(계속)

   }else if(command.equals("/BoardDetailAction.bo")){
	   action = new BoardDetailAction();    //수정완료 후 원래의 글로 이동 
	   try{
		   forward=action.execute(request, response);
	   }catch(Exception e){
		   e.printStackTrace();
	   }
   }

➡️Controller: BoardDetailAction

package net.board.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.board.db.BoardDAO;
import net.board.db.BoardBean;

 public class BoardDetailAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 throws Exception{ 
		request.setCharacterEncoding("euc-kr");
   		
		BoardDAO boarddao=new BoardDAO();
	   	BoardBean boarddata=new BoardBean();
	   	
		int num=Integer.parseInt(request.getParameter("num"));
		boarddao.setReadCountUpdate(num);
	   	boarddata=boarddao.getDetail(num);
	   	
	   	if(boarddata==null){
	   		System.out.println("게시글이 없습니다");
	   		return null;
	   	}
	   	System.out.println("조회완료");
	   	
	   	request.setAttribute("boarddata", boarddata);
	   	ActionForward forward = new ActionForward();
	   	forward.setRedirect(false);
   		forward.setPath("./board/qna_board_view.jsp");
   		return forward;

	 }
}

➡️Controller: BoardFrontController(계속)

 if(forward.isRedirect()){   //false
   response.sendRedirect(forward.getPath()); 
	    // "./board/qna_board_view.jsp"으로 이동
 }else{
   RequestDispatcher dispatcher=
	   request.getRequestDispatcher(forward.getPath());
   dispatcher.forward(request, response);
 }
}

5. 게시글 답변하기

  • qna_board_view(상세보기)에서 [답변] 선택
  • "./BoardReplyAction.bo?num=<%=board.getBOARD_NUM() %>"
  • getString방식 게시글번호 전송

➡️Controller: BoardFrontController

}else if(command.equals("/BoardReplyAction.bo")){
 action = new BoardReplyView();
 try{
   forward=action.execute(request, response);
 }catch(Exception e){
   e.printStackTrace();
 }

➡️Controller: BoardReplyView

package net.board.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.board.db.BoardDAO;
import net.board.db.BoardBean;

public class BoardReplyView implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 	throws Exception{
		 	ActionForward forward = new ActionForward();
		 	
			BoardDAO boarddao=new BoardDAO();
	   		BoardBean boarddata=new BoardBean();
	   		
	   		int num=Integer.parseInt(request.getParameter("num"));  //boardNum
	   		
	   		boarddata=boarddao.getDetail(num);

➡️Model: BoardDAO

	public BoardBean getDetail(int num) throws Exception {
	BoardBean board = null;
	try {
		con = ds.getConnection();
		pstmt = con.prepareStatement("select * from board where BOARD_NUM = ?");
		pstmt.setInt(1, num);

		rs = pstmt.executeQuery();

		if (rs.next()) {
			board = new BoardBean();
			board.setBOARD_NUM(rs.getInt("BOARD_NUM"));
			board.setBOARD_NAME(rs.getString("BOARD_NAME"));
			board.setBOARD_SUBJECT(rs.getString("BOARD_SUBJECT"));
			board.setBOARD_CONTENT(rs.getString("BOARD_CONTENT"));
			board.setBOARD_FILE(rs.getString("BOARD_FILE"));
			board.setBOARD_RE_REF(rs.getInt("BOARD_RE_REF"));
			board.setBOARD_RE_LEV(rs.getInt("BOARD_RE_LEV"));
			board.setBOARD_RE_SEQ(rs.getInt("BOARD_RE_SEQ"));
			board.setBOARD_READCOUNT(rs.getInt("BOARD_READCOUNT"));
			board.setBOARD_DATE(rs.getDate("BOARD_DATE"));
		}
		return board;
	} catch (Exception ex) {
		System.out.println("getDetail : " + ex);
	} finally {
		if (rs != null)
			try {
				rs.close();
			} catch (SQLException ex) {
			}
		if (pstmt != null)
			try {
				pstmt.close();
			} catch (SQLException ex) {
		}
		if(con != null)
			try {
				con.close();
			} catch(SQLException ex) {
				
		}
	}
	return null;
}

➡️Controller: BoardReplyView(계속)

	   		if(boarddata==null){
	   			System.out.println("데이터가 없습니다");
	   			return null;
	   		}
	   		System.out.println("데이터를 불러왔습니다.");
	   		
	   		request.setAttribute("boarddata", boarddata);
	   		
	   		forward.setRedirect(false);     //forward 설정
	   		forward.setPath("./board/qna_board_reply.jsp");
	   		return forward;
	}
}

➡️Controller: BoardFrontController(계속)

	   if(forward.isRedirect()){   //false
		   response.sendRedirect(forward.getPath());     
	   }else{
		   RequestDispatcher dispatcher=
			   request.getRequestDispatcher(forward.getPath());
		   dispatcher.forward(request, response);  //request = boarddata
	   }
 }

➡️ View: qna_board_reply.jsp (form action=”./BoardReplyView.bo" 이동)

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="net.board.db.*" %>
<%
	BoardBean board=(BoardBean)request.getAttribute("boarddata"); //답글 원글 데이터 불러오기
%>

<html>
<head>
	<title>MVC 게시판</title>
	<script language="javascript">
	function replyboard(){
		boardform.submit();
	}
	</script>
</head>
<body>
<!-- 게시판 답변 -->
<form action="./BoardReplyView.bo" method="post" name="boardform">
<input type="hidden" name="BOARD_NUM" value="<%=board.getBOARD_NUM() %>">
<input type="hidden" name="BOARD_RE_REF" value="<%=board.getBOARD_RE_REF() %>">
<input type="hidden" name="BOARD_RE_LEV" value="<%=board.getBOARD_RE_LEV() %>">
<input type="hidden" name="BOARD_RE_SEQ" value="<%=board.getBOARD_RE_SEQ() %>">

<table cellpadding="0" cellspacing="0">
	<tr align="center" valign="middle">
		<td colspan="5">MVC 게시판</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">글쓴이</div>
		</td>
		<td>
			<input name="BOARD_NAME" type="text"/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">제 목</div>
		</td>
		<td>
			<input name="BOARD_SUBJECT" type="text" size="50" 
				maxlength="100" value="Re: <%=board.getBOARD_SUBJECT() %>"/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">내 용</div>
		</td>
		<td>
			<textarea name="BOARD_CONTENT" cols="67" rows="15"></textarea>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">비밀번호</div>
		</td>
		<td>
			<input name="BOARD_PASS" type="password">
		</td>
	</tr>
	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	
	<tr align="center" valign="middle">
		<td colspan="5">
		<a href="javascript:replyboard()">[등록]</a>&nbsp;&nbsp;
		<a href="javascript:history.go(-1)">[뒤로]</a>
		</td>
	</tr>
</table>
</form>
<!-- 게시판 답변 -->
</body>
</html>

➡️Controller: BoardFrontController(계속)

 }else if(command.equals("/BoardReplyView.bo")){
   action = new BoardReplyAction();   
   try{
	   forward=action.execute(request, response);
   }catch(Exception e){
	   e.printStackTrace();
   }

➡️Controller: BoardReplyAction

package net.board.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.board.db.BoardDAO;
import net.board.db.BoardBean;

public class BoardReplyAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 throws Exception{
		 	request.setCharacterEncoding("euc-kr");
		 	ActionForward forward = new ActionForward();
		 	
			BoardDAO boarddao=new BoardDAO();
	   	BoardBean boarddata=new BoardBean();
   		int result=0;
   		
   		boarddata.setBOARD_NUM(Integer.parseInt(request.getParameter("BOARD_NUM")));
   		boarddata.setBOARD_NAME(request.getParameter("BOARD_NAME"));
   		boarddata.setBOARD_PASS(request.getParameter("BOARD_PASS"));
   		boarddata.setBOARD_SUBJECT(request.getParameter("BOARD_SUBJECT"));
   		boarddata.setBOARD_CONTENT(request.getParameter("BOARD_CONTENT"));
   		boarddata.setBOARD_RE_REF(Integer.parseInt(request.getParameter("BOARD_RE_REF")));
   		boarddata.setBOARD_RE_LEV(Integer.parseInt(request.getParameter("BOARD_RE_LEV")));
   		boarddata.setBOARD_RE_SEQ(Integer.parseInt(request.getParameter("BOARD_RE_SEQ")));
   		
   		result=boarddao.boardReply(boarddata);

➡️Model: BoardDAO(계속)

	public int boardReply(BoardBean board) {
		String board_max_sql = "select max(board_num) from board";
		String sql = "";
		int num = 0;
		int result = 0;

		int re_ref = board.getBOARD_RE_REF();
		int re_lev = board.getBOARD_RE_LEV();
		int re_seq = board.getBOARD_RE_SEQ();

		try {
			con = ds.getConnection();
			pstmt = con.prepareStatement(board_max_sql);
			rs = pstmt.executeQuery();
			if (rs.next())
				num = rs.getInt(1) + 1;
			else
				num = 1;

			sql = "update board set BOARD_RE_SEQ=BOARD_RE_SEQ+1 where BOARD_RE_REF=? ";
			sql += "and BOARD_RE_SEQ>?";

			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, re_ref);
			pstmt.setInt(2, re_seq);
			result = pstmt.executeUpdate();

			re_seq = re_seq + 1;
			re_lev = re_lev + 1;

			sql = "insert into board (BOARD_NUM,BOARD_NAME,BOARD_PASS,BOARD_SUBJECT,";
			sql += "BOARD_CONTENT, BOARD_FILE,BOARD_RE_REF,BOARD_RE_LEV,BOARD_RE_SEQ,";
			sql += "BOARD_READCOUNT,BOARD_DATE) values(?,?,?,?,?,?,?,?,?,?,sysdate())";

			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.setString(2, board.getBOARD_NAME());
			pstmt.setString(3, board.getBOARD_PASS());
			pstmt.setString(4, board.getBOARD_SUBJECT());
			pstmt.setString(5, board.getBOARD_CONTENT());
			pstmt.setString(6, ""); 
			pstmt.setInt(7, re_ref);
			pstmt.setInt(8, re_lev);
			pstmt.setInt(9, re_seq);
			pstmt.setInt(10, 0);
			pstmt.executeUpdate();
			return num;
		} catch (SQLException ex) {
			System.out.println("boardReply : " + ex);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException ex) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException ex) {
			}
			if(con != null)
				try {
					con.close();
				} catch(SQLException ex) {
					
			}
		}
		return 0;
	}

}

➡️Controller: BoardReplyAction(계속)

   		if(result==0){
   			System.out.println("댓글 오류가 발생했습니다");
   			return null;
   		}
   		System.out.println("댓글 완료");
   		
   		forward.setRedirect(true); 
   		forward.setPath("./BoardDetailAction.bo?num="+result);
   		return forward;
	}  	
}

➡️Controller: BoardFrontController(계속)

	   if(forward.isRedirect()){   //true 
		   response.sendRedirect(forward.getPath());  //"./BoardDetailAction.bo?num="+result
	   }else{
		   RequestDispatcher dispatcher=
			   request.getRequestDispatcher(forward.getPath());
		   dispatcher.forward(request, response);  //request = boarddata
	   }
 }

➡️Controller: BoardFrontController(계속)

		   }else if(command.equals("/BoardDetailAction.bo")){
			   action = new BoardDetailAction();
			   try{
				   forward=action.execute(request, response);
			   }catch(Exception e){
				   e.printStackTrace();
			   }
		   }
		   

➡️Controller: BoardDetailAction

 public class BoardDetailAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{ 
		request.setCharacterEncoding("euc-kr");
   		
		BoardDAO boarddao=new BoardDAO();
	   	BoardBean boarddata=new BoardBean();
	   	
		int num=Integer.parseInt(request.getParameter("num"));
		boarddao.setReadCountUpdate(num);
	   	boarddata=boarddao.getDetail(num);
	   	
	   	if(boarddata==null){
	   		System.out.println("게시글이 없습니다");
	   		return null;
	   	}
	   	System.out.println("조회완료");
	   	
	   	request.setAttribute("boarddata", boarddata);
	   	ActionForward forward = new ActionForward();
	   	forward.setRedirect(false);
   		forward.setPath("./board/qna_board_view.jsp");
   		return forward;

	 }
}

➡️Controller: BoardFrontController(계속)

	   if(forward.isRedirect()){   //true 
		   response.sendRedirect(forward.getPath());  //"./BoardDetailAction.bo?num="+result
	   }else{
		   RequestDispatcher dispatcher=
			   request.getRequestDispatcher(forward.getPath());
		   dispatcher.forward(request, response);  //request = boarddata
	   }
 }

➡️View : qna_board_view

6. 게시글 삭제하기

  • qna_board_view(상세보기)에서 [삭제] 선택
  • "./BoardDelete.bo?num=<%=board.getBOARD_NUM() %>>" getString방식 게시글번호 전송

➡️Controller: BoardFrontController

 }else if(command.equals("/BoardDeleteAction.bo")){
	   action = new BoardDeleteAction(); 
	   try{
		   forward=action.execute(request, response);
	   }catch(Exception e){
		   e.printStackTrace();
	   }

➡️Controller: BoardDeleteAction

package net.board.action;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.board.db.*;

public class BoardDeleteAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) 
	 	throws Exception{
		 
		ActionForward forward = new ActionForward();
		request.setCharacterEncoding("euc-kr");
		
	   	boolean result=false;
	   	boolean usercheck=false;
	   	int num=Integer.parseInt(request.getParameter("num"));  //해당 글 num
	   	
	   	BoardDAO boarddao=new BoardDAO();
	   	usercheck=boarddao.isBoardWriter(num, request.getParameter("BOARD_PASS"));

➡️Model: BoardDAO(계속)

	public boolean isBoardWriter(int num, String pass) {
		String board_sql = "select * from board where BOARD_NUM=?";
		int result = 0;

		try {
			con = ds.getConnection();
			pstmt = con.prepareStatement(board_sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			rs.next();

			if (pass.equals(rs.getString("BOARD_PASS"))) {
				result = 1;
			}
		} catch (SQLException ex) {
			System.out.println("isBoardWriter =: " + ex);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException ex) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException ex) {
			}
			if(con != null)
				try {
					con.close();
				} catch(SQLException ex) {
					
			}
		}
		if (result != 0) {
			return true;
		} else {
			return false;
		}

	}

➡️Controller: BoardDeleteAction(계속)

 	if(usercheck==false){
		response.setContentType("text/html;charset=euc-kr");
		PrintWriter out=response.getWriter();
		out.println("<script>");
		out.println("alert('비밀번호가 일치하지 않습니다.');");
		out.println("location.href='./BoardList.bo';");
		out.println("</script>");
		out.close();
		return null;
	}
	
	result=boarddao.boardDelete(num);

➡️Model: BoardDAO(계속)

	public boolean boardDelete(int num) {

		String board_delete_sql = "delete from board where BOARD_num=?";

		int result = 0;

		try {
			con = ds.getConnection();
			pstmt = con.prepareStatement(board_delete_sql);
			pstmt.setInt(1, num);
			result = pstmt.executeUpdate();
			if (result == 0)
				return false;

			return true;
		} catch (Exception ex) {
			System.out.println("boardDelete: " + ex);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException ex) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException ex) {
			}
			if(con != null)
				try {
					con.close();
				} catch(SQLException ex) {
					
			}
		}

		return false;

➡️Controller: BoardDeleteAction(계속)

   	result=boarddao.boardDelete(num);
	   	if(result==false){
	   		System.out.println("삭제에 실패하였습니다");
	   		return null;
	   	}
	   	
	   	System.out.println("삭제하였습니다");
	   	forward.setRedirect(true);
   		forward.setPath("./BoardList.bo");
   		return forward;
	 }

'BackEnd > JSP' 카테고리의 다른 글

[JSP]영역 객체(Scope)  (0) 2024.05.17
[JSP] Java Beans  (0) 2024.05.16
[JSP]JSTL(Jsp Standard Tag Library) CORE 태그  (0) 2024.05.16