20221024-63 Spring(6) MVC2 게시판 만들기(글조회,조회수,수정,삭제,글쓰기,댓글)

공현지·2022년 10월 24일
0

spring

목록 보기
4/30

게시글 (상세내용) 조회하기

bController.java

 @RequestMapping("/content_view")
  public String content_view(HttpServletRequest request, Model model) {
	  System.out.println("content_view()");
	                      //이름    //객체 
	  model.addAttribute("request" , request); 
      //request를 모델에 저장해놓고 request를 사용 service에서 사용가능 
	  command = new BContentCommand() ;
	  command.execute(model);
	  
	  return "content_view";
		

  }


BContentCommand


public class BContentCommand implements BCommand {

	@Override
	public void execute(Model model) {
		   //모델을 맵으로 전환
		 Map<String, Object> map = model.asMap();
		                         //2값 이 들어옴         //1키 이름 호출해서  
		 HttpServletRequest request = (HttpServletRequest) map.get("request"); //맵에서 request를 가져온다  
                                                                   //BContentCommand에서 request에서 
	    String bId = request.getParameter("bId");
	    
	    BDao dao = new BDao();
	    BDto board = dao.contentView(bId);
	                               //mvc_board에 객체를 담아서 보냄
	    model.addAttribute("mvc_board", board);
	    
	    
	}                                           



list.jsp에서
a href= "content_view?bId="mvcboard.bId">{mvc_board.bId}">{mvc_board.bTitle}a
bId로 옮겨줫기 때문에 BContentCommand에서 겟파라메터로 받을수있음

BDao.java

public String contentView(String strId) {
		upHit(strId); //조회수 올리는것 
        BDto dto = null;

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		System.out.println("BDao contentView start...");

		try {
			conn = dataSource.getConnection();
			String sql = "select*from mvc_board where bId = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(strId));
			System.out.println("boardList sql->" + sql);
			rs = pstmt.executeQuery();

			if (rs.next()) { // 1 dto에서 다불러와서
				int bId = rs.getInt("bId");
				String bName = rs.getString("bName");
				String bTitle = rs.getString("bTitle");
				String bContent = rs.getString("bContent");
				Timestamp bDate = rs.getTimestamp("bDate");
				int bHit = rs.getInt("bHit");
				int bGroup = rs.getInt("bGroup");
				int bStep = rs.getInt("bStep");
				int bIndent = rs.getInt("bIndent");
			    dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
			}
		} catch (Exception e) {
			System.out.println("list dataSource-->" + e.getMessage());

		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}
		} // 5리턴 bList 해주기
		return "dto";

	}
}




뷰단 작성 ContentView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ include file="header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
			<form action="modify" method="post">
						<input type="hidden" name="bId" value="${mvc_board.bId }">
						<table border="1" >
						  <tr>
						    <td>번호</td>   <td>${mvc_board.bId }</td>
						  </tr>
						  <tr>
						    <td>히트</td>   <td>${mvc_board.bHit }</td>
						  </tr>
						    <tr>
						    <td>이름</td>   <td><input type="text" name="bName" value="${mvc_board.bName }"></td>
						  </tr>
						    <tr>
						    <td>제목</td>   <td><input type="bTitle"  value="${mvc_board.bTitle}"></td>
						  </tr>
						<tr>
						  <td>내용</td>
						  <td> <textarea rows="10" name="bContent">${mvc_board.bContent}</textarea> </td>
						</tr>
						<tr>
						<td colspan="2" > <input type="submit"  value="수정 "> &nbsp;&nbsp;
						<a href="list">목록보기</a> &nbsp;&nbsp;
						<a href="delete?bId=${mvc_board.bId}">삭제</a> &nbsp;&nbsp;
						<a href="reply_veiw?bId=${mvc_board.bId}">답변</a> &nbsp;&nbsp;
						
						</td>
						
						</tr>
						
						
						</table>
	
			
			</form>


</body>
</html>



조회수 올리기

BDao.java

private void upHit(String bId) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		System.out.println("BDao upHit start...");

		try {
			conn = dataSource.getConnection();
			String sql = "update mvc_board set bHit = bHit + 1 where bId= ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, bId);
			int rn = pstmt.executeUpdate(); // 업데이트 할때 다시 인트로 돌려줌

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}
		}

	}




게시글 조회 목록 + 조회수 올리기


게시글 수정

BController.java

 
    //모델에 담아서 보내야함 
  @RequestMapping(value = "/modify" , method = RequestMethod.POST)
     public String modify(HttpServletRequest request, Model model) {
	  logger.info("modify start .. . ");
	  model.addAttribute("request", request);
	  command = new BModifyCommand();
	  command.execute(model);
    	 
 
	  return "redirect:list"; // 다시 list로 되돌리기 
}
  

BmodifyCommand.java

package com.oracle.oMVCBoard.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.oracle.oMVCBoard.dao.BDao;

public class BModifyCommand implements BCommand {

    @Override
   public void execute(Model model) {
      // 1. model을 Map 선언
      Map<String, Object> map = model.asMap();
      //2) request 이용 ->  request추출 
      HttpServletRequest request = (HttpServletRequest) map.get("request");
      // 2. parameter로이용 bId, bName, bTitle, bContent 추출
      String bId = request.getParameter("bId");
      String bName = request.getParameter("bName");
      String bTitle = request.getParameter("bTitle");
      String bContent = request.getParameter("bContent");
      //3) dao  instance 선언
      BDao dao = new BDao();
   // 4) modify method 이용하여 삭제
      dao.modify(bId, bName, bTitle, bContent);
   }
}

BDao.java

	public void modify(String bId, String bName, String bTitle, String bContent) {
	      Connection conn = null;
	      PreparedStatement pstmt = null;
	      
	      System.out.println("BDao modify start...");
	      
	      try {
	         conn = dataSource.getConnection();
	         String sql = "update mvc_board set bName=?, bTitle=?, bContent=? where bId=?";
	         pstmt = conn.prepareStatement(sql);
	         pstmt.setString(1, bName);
	         pstmt.setString(2, bTitle);
	         pstmt.setString(3, bContent);
	         pstmt.setInt(4, Integer.parseInt(bId));
	         pstmt.executeUpdate();
	      } catch (Exception e) {
	         System.out.println("modify dataSource-->"+e.getMessage());
	      } finally {
	         try {
	            if( pstmt!=   null ) pstmt.close();
	            if( conn !=   null )  conn.close();
	         } catch (Exception e2) {
	            System.out.println(e2.getMessage());
	         }
	      }
	}

게시글 삭제

BController.java


   @RequestMapping("/delete")
  public String delete(HttpServletRequest request, Model model) {
	  System.out.println("delect()");
	   
	  model.addAttribute("request", request);
	  command= new BDeleteCommand();
	  command.execute(model);
	  
	  return "redirect:list"; 
  }
  

과제
1.BDeleteCommand Service 파일 생성
1) model이용 , map 선언
2) request 이용 -> bId 추출
3) dao instance 선언
4) delete method 이용하여 삭제

BDeleteCommand.java

package com.oracle.oMVCBoard.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.oracle.oMVCBoard.dao.BDao;

public class BDeleteCommand implements BCommand {

	@Override
	public void execute(Model model) {
		  // 1. model을 Map 선언
	      Map<String, Object> map = model.asMap();
	    
	     // 2) request 이용 ->  bId 추출
	      HttpServletRequest request = (HttpServletRequest) map.get("request");
	      String bId = request.getParameter("bId");
	      
	     // 3) dao  instance 선언
         BDao dao = new BDao();
	     // 4) delete method 이용하여 삭제
	      dao.delete(bId);
	
	}

}


BDao.java

public void delete(String strId) {
	      Connection conn = null;
	      PreparedStatement pstmt = null;
	      
	      System.out.println("BDao delete start...");
	      
	    try {
	 
	       conn = dataSource.getConnection();
	       String sql = "delete from mvc_board where bId =? ";
	       System.out.println("delete sql->"+sql);
	       pstmt = conn.prepareStatement(sql);
	       pstmt.setInt(1,Integer.parseInt(strId));
			int rn = pstmt.executeUpdate();
	       
	       
	    }catch (SQLException e) {
	    	 System.out.println("delete dataSource-->"+e.getMessage());
			e.printStackTrace();
	    } finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());

			}

			
	    }
	}
	
	    }
	

게시 글작성 화면

BController.java

 @RequestMapping("/write_view")
  public String write_view(Model model) {
	  logger.info("write_view start. . ");
	  
      return "write_view";
	  
  }
  

write_view.jsp(뷰작성)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="write" method="post">
		<table width="500" border="1">
			<tr>
				<td>이름</td>
				<td><input type="text" name="bName" size="50"></td>
			</tr>
			<tr>
				<td>제목</td>
				<td><input type="text" name="bTitle" size="50"></td>
			</tr>
			<tr>
				<td>내용</td>
				<td><textarea name="bContent" rows="10"></textarea></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="입력"> <a
					href="list">목록보기</a></td>
				</td>
			</tr>
		</table>

	</form>

</body>
</html>

게시 글쓰기(글작성)

BController.java

@PostMapping(value = "/write")
	public String write(HttpServletRequest request, Model model) {
		logger.info("write start...");

		model.addAttribute("request", request);
		command = new BWriteCommand();
		command.execute(model);
		return "redirect:list";
	}

과제

1.BWriteCommand Service 파일 생성
1) model이용 , map 선언
2) request 이용 -> bName ,bTitle , bContent 추출
3) dao instance 선언
4) write method 이용하여 저장(bName, bTitle, bContent)

BWriteCommand.java


package com.oracle.oMVCBoard.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.oracle.oMVCBoard.dao.BDao;

public class BWriteCommand implements BCommand {

   @Override
   public void execute(Model model) {
   
 // 1)  model이용 , map 선언
 // 2) request 이용 ->  bName  ,bTitle  , bContent  추출
 // 3) dao  instance 선언
 // 4) write method 이용하여 저장(bName, bTitle, bContent)
      
      Map<String, Object> map = model.asMap();
      HttpServletRequest request = (HttpServletRequest) map.get("request");
      String bName = request.getParameter("bName");
      String bTitle = request.getParameter("bTitle");
      String bContent = request.getParameter("bContent");
      
      BDao dao = new BDao();
      dao.write(bName, bTitle, bContent);
   }

}

BDao.java

	public void write(String bName, String bTitle, String bContent) {
		Connection conn = null;
		PreparedStatement pstmt = null;

		System.out.println("BDao write start...");

		try {
			conn = dataSource.getConnection();
			String sql = "insert into mvc_board(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent) "
					+ "values(mvc_board_seq.nextval,?,?,?,sysdate,0,mvc_board_seq.currval,0,0)";
			System.out.println("BDao write sql->" + sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, bName);
			pstmt.setString(2, bTitle);
			pstmt.setString(3, bContent);
			int rn = pstmt.executeUpdate();
		} catch (Exception e) {
			System.out.println("write dataSource-->" + e.getMessage());
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}
		}
	}



댓글창화면(답변창)

BController.java

@RequestMapping("reply_view")
	public String reply_view(HttpServletRequest request, Model model) {
		logger.info("reply_view start. . ");
		model.addAttribute("requset", request);
		command = new BReplyViewCommand();
		command.execute(model);
		
		return "reply_view";

	}

reply_view.jsp (뷰단 작성)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ include file="header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="reply" method="post">
         <input type="hidden" name="bId" value="${reply_view.bId }">
         <input type="hidden" name="bGroup" value="${reply_view.bGroup }">
         <input type="hidden" name="bStep" value="${reply_view.bStep }">
         <input type="hidden" name="bIndent" value="${reply_view.bIndent }">
         <table  width = "500"  border="1">
         			<tr>
         			   <td>번호</td><td>${reply_view.bId }</td>
         			</tr>
         			<tr>
         			   <td>히트</td><td>${reply_view.bHit}</td>
         			</tr>
         			<tr>
         					<td>이름</td><td><input type="text" name="bName" value="${reply_view.bName }"></td>
         			</tr>
         			<tr>
         					<td>제목</td><td><input type="text" name="bTitle" value="답변"+"${reply_view.bTitle }"></td>
         			</tr>
                    <tr>
                    <td>내용</td>
                    <td> <textarea rows="10" name="bContent"></textarea>${reply_view.bContent}</td>
                    </tr>
         			<tr>
         			<td colspan="2"><input type="submit" value="답변저장">
         			 <a href="list">목록</a> </td>
         			</tr>
         
         
         </table>
      
    
    </form>



</body>
</html>

1.BReplyViewCommand Service 파일 생성
1) model이용 , map 선언
2) request 이용 -> bid 추출
3) dao instance 선언
4) reply_view method 이용하여 (bid)
- BDto dto = dao.reply_view(bId);

BReplyViewCommand.java

package com.oracle.oMVCBoard.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.oracle.oMVCBoard.dao.BDao;
import com.oracle.oMVCBoard.dto.BDto;

public class BReplyViewCommand implements BCommand {
   //답변작성할수 있는 화면 
	@Override
	public void execute(Model model) {
		 Map<String, Object> map = model.asMap();
		    
	      HttpServletRequest request = (HttpServletRequest) map.get("request");
	      String bId = request.getParameter("bId");
	   

         BDao dao = new BDao();
         BDto dto = dao.reply_view(bId);	

         model.addAttribute("reply_view" , dto);
         

	}

}

BDao.java

public BDto reply_view(String str) {
		BDto dto = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		System.out.println("BDao reply_view start...");
		try {

			conn = dataSource.getConnection();
			String sql = "select * from mvc_board where bId= ? ";
			System.out.println("delete sql->" + sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(str));
			int rn = pstmt.executeUpdate();

			if (rs.next()) { // 1 dto에서 다불러와서
				int bId = rs.getInt("bId");
				String bName = rs.getString("bName");
				String bTitle = rs.getString("bTitle");
				String bContent = rs.getString("bContent");
				Timestamp bDate = rs.getTimestamp("bDate");
				int bHit = rs.getInt("bHit");
				int bGroup = rs.getInt("bGroup");
				int bStep = rs.getInt("bStep");
				int bIndent = rs.getInt("bIndent");
				dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);

			}
		} catch (SQLException e) {
			System.out.println("reply_view dataSource-->" + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());

			}

		}
		return dto;

	}



댓글작성(댓글달기)

BController.java

 @RequestMapping(value="/reply", method = RequestMethod.POST ) public String
	 reply(HttpServletRequest request, Model model) { 
		  logger.info("reply()");
	 
	  model.addAttribute("request", request); command = new BReplyCommand();
	  command.execute(model);
	  
	  return "redirect:list";
	  }


1.BReplyCommand Service 파일 생성
1) model이용 , map 선언
2) request 이용 -> bid, bName , bTitle,
bContent ,bGroup ,bStep ,
bIndent 추출
3) dao instance 선언
4) reply method 이용하여 댓글저장
- dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);

BReplyCommand.java


package com.oracle.oMVCBoard.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.oracle.oMVCBoard.dao.BDao;

public class BReplyCommand implements BCommand {

	@Override
	public void execute(Model model) {
		// TODO Auto-generated method stub

		 // 1)  model이용 , map 선언
		   Map<String, Object> map = model.asMap();
		//  2) request 이용 ->  bid,      bName , bTitle,
		  //                          bContent ,bGroup  ,bStep ,
		  //                          bIndent 추출
		   HttpServletRequest request = (HttpServletRequest) map.get("request");
		   String bId = request.getParameter("bId");
		      String bName = request.getParameter("bName");
		      String bTitle = request.getParameter("bTitle");
		      String bContent = request.getParameter("bContent");
		      String bGroup = request.getParameter("bGroup");
		      String bStep = request.getParameter("bStep");
		      String bIndent = request.getParameter("bIndent");
		//  3) dao  instance 선언
		 // 4) reply method 이용하여 댓글저장 
		 //   - dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);
		      BDao dao = new BDao();
		      dao.reply (bId, bName, bTitle, bContent,bGroup, bStep, bIndent);
		
		
		
	}

}




BDao.java



	public void reply(String bId, String bName, String bTitle, String bContent,String bGroup, String bStep, String bIndent) {
	 
	 Connection conn = null; PreparedStatement pstmt = null;
	 
	 System.out.println("BDao reply_view start..."); 
	 try {
	 
	 conn = dataSource.getConnection(); 
	 String sql ="insert into mvc_board (bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent) "
	 		                                                + "values (mvc_board_seq.nextval,?,?,?,sysdate,0,?,?,?)"; 
	 
	 String sql2 = "update mvc_board set bStep = bStep +1 where bGroup=? and bStep > ?";

	  pstmt = conn.prepareStatement(sql2);
      pstmt.setInt(1, Integer.parseInt(bGroup)); 
      pstmt.setInt(2,Integer.parseInt(bStep));
      pstmt.executeUpdate();
      pstmt.close();

	 System.out.println("reply_view sql->"+sql); 
	 pstmt =conn.prepareStatement(sql); 
	  pstmt.setString(1,bName );
	  pstmt.setString(2,bTitle );
	  pstmt.setString(3,bContent ); 
	  pstmt.setInt(4, Integer.parseInt(bGroup)); 
	  pstmt.setInt(5, Integer.parseInt(bStep) + 1);
	  pstmt.setInt(6, Integer.parseInt(bIndent) + 1);
	  
	 int rn = pstmt.executeUpdate();

	  }catch( Exception e) { 
		  System.out.println("reply_view dataSource-->" + e.getMessage()); e.printStackTrace();
      }finally { 
    	  try { 
    		  if (pstmt != null) pstmt.close();
    		  if (conn != null) conn.close();
    		  } catch (Exception e2) {
	  System.out.println(e2.getMessage());
	 
	 }
	 
	 } 
	 
	}


위에꺼랑 똑같지만 sql두개 쓰지않고 댓글 나눠서 쓰는법


public void reply(String bId, String bName, String bTitle, String bContent,String bGroup, String bStep, String bIndent) {
	                       //이렇게 많으면 dto로 가져와도 됨 
		
	//홍해의 기적 replyShape(bGroup, brStep)은 따로 뺼수도 있음 sql2
	replyShape(bGroup, bStep);
		
	 Connection conn = null; 
	 PreparedStatement pstmt = null;
	 
	 System.out.println("BDao reply_view start..."); 
	 try {  
	 
	 conn = dataSource.getConnection(); 
	 String sql ="insert into mvc_board (bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent) "
	 		                                                + "values (mvc_board_seq.nextval,?,?,?,sysdate,0,?,?,?)"; 
	 

	 System.out.println("reply_view sql->"+sql); 
	 pstmt =conn.prepareStatement(sql); 
	  pstmt.setString(1,bName );
	  pstmt.setString(2,bTitle );
	  pstmt.setString(3,bContent ); 
	  pstmt.setInt(4, Integer.parseInt(bGroup)); 
	  pstmt.setInt(5, Integer.parseInt(bStep) + 1);
	  pstmt.setInt(6, Integer.parseInt(bIndent) + 1);
	  
	 int rn = pstmt.executeUpdate();

	  }catch( Exception e) { 
		  System.out.println("reply_view dataSource-->" + e.getMessage()); e.printStackTrace();
      }finally { 
    	  try { 
    		  if (pstmt != null) pstmt.close();
    		  if (conn != null) conn.close();
    		  } catch (Exception e2) {
	  System.out.println(e2.getMessage());
	 
	 }
	 
	 } 
	 
	}

	  //댓글에서  bGroup bStep 따로 뺴준것 
	private void replyShape(String strGroup, String strStep) {
		 Connection conn = null; 
		 PreparedStatement pstmt = null;
		 
		 System.out.println("BDao replyShape start..."); 
		 try {  
			 String sql = "update mvc_board set bStep = bStep +1 where bGroup=? and bStep > ?";

			  pstmt = conn.prepareStatement(sql);
		      pstmt.setInt(1, Integer.parseInt(strGroup)); 
		      pstmt.setInt(2,Integer.parseInt(strStep));
		      pstmt.executeUpdate();
		 
			 
		      int rn = pstmt.executeUpdate();
			 
	 }catch( Exception e) { 
		  System.out.println("replyShapeSource-->" + e.getMessage()); e.printStackTrace();
    }finally { 
  	  try { 
  		  if (pstmt != null) pstmt.close();
  		  if (conn != null) conn.close();
  		  } catch (Exception e2) {
	  System.out.println(e2.getMessage());
	 
	 }
	 
	 } 
	 

	}
}










0개의 댓글