본문 바로가기
강의/JSP 강의 정리

JSP 강의 정리 19일차

by 리드민 2022. 8. 1.
반응형

[1] 테스트 환경

hardware
cpu : intel i7-7700, gpu : intel hd 630, ram : ddr4 16GB, mainboard : samsung DB400S7A-Z51, secondary storage : 256GB SSD, 1TB HDD
OS
windows pro 64bits
software
jdk version 1.8.0_301
eclipse version 2021-09 (4.21.0)
apache-tomcat version 9.0.54

 

[2] 강의 정리

 

() 게시판 만들기

sql 쿼리문

create table board (
    bId number(4) primary key, -- 유일한 값
    bName nvarchar2(20) not null, -- 작성자
    bTitle nvarchar2(100) not null, -- 제목
    bContent nvarchar2(500) not null, -- 내용
    bDate timestamp default systimestamp, -- 작성일
    bHit number(4) default 0 -- 조회수
);

CREATE SEQUENCE board_seq -- 시퀀스 (자동으로 증가하는 순번)
START WITH 1 -- 시퀀스 값 1 부터
INCREMENT BY 1 -- 1씩 증가
NOMAXVALUE -- 시퀀스의 범위를 무한대로 지정
NOCACHE; -- 캐시값 없애기

commit;

 

프로젝트 폴더 > src/main/java

com.jsp.board

BoardDTO.java

package com.jsp.board;

import java.sql.Timestamp;

public class BoardDTO {

	private int bId;
	private String bName;
	private String bTitle;
	private String bContent;
	private Timestamp bDate;
	private int bHit;
	
	public BoardDTO() {}

	public BoardDTO(int bId, String bName, String bTitle, String bContent, Timestamp bDate, int bHit) {
		super();
		this.bId = bId;
		this.bName = bName;
		this.bTitle = bTitle;
		this.bContent = bContent;
		this.bDate = bDate;
		this.bHit = bHit;
	}

	public int getbId() {
		return bId;
	}

	public void setbId(int bId) {
		this.bId = bId;
	}

	public String getbName() {
		return bName;
	}

	public void setbName(String bName) {
		this.bName = bName;
	}

	public String getbTitle() {
		return bTitle;
	}

	public void setbTitle(String bTitle) {
		this.bTitle = bTitle;
	}

	public String getbContent() {
		return bContent;
	}

	public void setbContent(String bContent) {
		this.bContent = bContent;
	}

	public Timestamp getbDate() {
		return bDate;
	}

	public void setbDate(Timestamp bDate) {
		this.bDate = bDate;
	}

	public int getbHit() {
		return bHit;
	}

	public void setbHit(int bHit) {
		this.bHit = bHit;
	}
	
	
}

 

 

프로젝트 폴더 > src/main/java

com.jsp.board

BoardDAO.java

package com.jsp.board;

import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class BoardDAO {
	
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private DataSource ds;
	
	private BoardDAO() {
		try {
			
			Context context = new InitialContext();
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle");
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private static BoardDAO instance = new BoardDAO();
	
	public static BoardDAO getInstance() {
		return instance;
	}
	
	
	private void close(Connection conn) {
		try {
			if(conn != null) {
				conn.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void close(PreparedStatement pstmt) {
		try {
			if(pstmt != null) {
				pstmt.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void close(ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	// 게시판 목록을 보여주기 위한 메소드
	public ArrayList<BoardDTO> boardList(){
		
		ArrayList<BoardDTO> list = new ArrayList<BoardDTO>();
		
		String query = "select * from board order by bId DESC";
		// bId를 내림차순으로 정렬
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				
				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");
				
				list.add(new BoardDTO(bId, bName, bTitle, bContent, bDate, bHit));
				
			}
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(rs);
			close(pstmt);
			close(conn);
			
		}
		
		
		return list;
	}
	
	// 글 작성 후 데이터를 넣는 메소드
	public int write(String bName, String bTitle, String bContent) {
		int result = 0;
		
		String query = "insert into board(bId, bName, bTitle, bContent) "
				+ "values(board_seq.nextval, ?, ?, ?)";
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			
			pstmt.setString(1, bName);
			pstmt.setString(2, bTitle);
			pstmt.setString(3, bContent);
			
			result = pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(pstmt);
			close(conn);
			
		}
		
		return result;
	}
	
	// 리스트에 제목 클릭 시 해당 내용을 보여주기 위한 메소드
	public BoardDTO contentView(String strID) {
		BoardDTO dto = null;
		upHit(strID);
		
		String query = "select * from board where bId = ?";
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			
			pstmt.setInt(1, Integer.parseInt(strID));
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				
				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");
				
				dto = new BoardDTO(bId, bName, bTitle, bContent, bDate, bHit);
				
			}
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(rs);
			close(pstmt);
			close(conn);
			
		}
		
		return dto;
	}


	// 조회수 증가시켜주는 메소드 (bHit 하나 올려주는 메소드)
	private void upHit(String strID) {
		
		String query = "update board set bHit = bHit + 1 where bId = ?";
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, Integer.parseInt(strID));
			
			pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(pstmt);
			close(conn);
			
		}
		
		
	}
	
	
	// 해당글을 수정 해주는 메소드
	public int modify(String strID, String bName, String bTitle, String bContent) {
		int result = 0;
		
		String query = "update board set bName = ?, "
				+ "bTitle = ?, bContent = ? where bId = ?";
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			
			pstmt.setString(1, bName);
			pstmt.setString(2, bTitle);
			pstmt.setString(3, bContent);
			pstmt.setInt(4, Integer.parseInt(strID));
			
			result = pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(pstmt);
			close(conn);
			
		}
		
		
		return result;
	}
	
	// 해당글을 삭제 해주는 메소드
	public int delete(String strID) {
		int result = 0;
		
		String query = "delete from board where bId = ?";
		
		try {
			
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, Integer.parseInt(strID));
			
			result = pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
			close(pstmt);
			close(conn);
			
		}
		
		return result;
	}
	
	
}

 

boardList.jsp

<%@page import="com.jsp.board.BoardDTO"%>
<%@page import="com.jsp.board.BoardDAO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%-- JSTL --%>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- 부트스트랩 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<title>Insert title here</title>

</head>
<body>

<%
	
	// 1. DAO 객체 생성하기 
	// 2. boardList 메소드 호출하여 ArrayList 얻기
	// 3. list를 request영역에 바인딩하기
	
%>
	
	<br><br><h1 style="text-align : center;">나의 게시판</h1><br><br>
	
	<table class="table table-bordered">
	  <thead>
	    <tr>
	      <th scope="col">번호</th>
	      <th scope="col">이름</th>
	      <th scope="col">제목</th>
	      <th scope="col">날짜</th>
	      <th scope="col">조회수</th>
	    </tr>
	  </thead>
	  <tbody>
	  	
	  <%--
	  	EL 과 jstl로 게시판 목록 출력하기
	   --%>
	   
	    <tr>
	    	<td colspan="5" style="text-align: center"> 
	    		<a href="writeForm.jsp">글작성</a> 
	    	</td>
	    </tr>
	  </tbody>
	</table>
	
  	<!-- 부트스트랩 자바스크립트 -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

 

contentView.jsp

<%@page import="com.jsp.board.BoardDTO"%>
<%@page import="com.jsp.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<!-- 부트스트랩 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<style type="text/css">
	table{
		width : 50% !important;
		margin-left:25%; 
    	margin-right:25%;
		
	}
</style>

</head>
<body>

<%
	
	// 1. 넘어온 bId 받기
	// 2. DAO 객체 생성 후 contentView 메소드 호출하여 DTO 객체얻기
	// 3. DTO 객체를 "content_view" 이름으로 바인딩하기 
	
%>
	
	<br><br>
	
	<form action="modifyForm.jsp" method="post" accept-charset="UTF-8">
		<input type="hidden" name="bId" value="">
		<input type="hidden" name="bName" value="">
		<input type="hidden" name="bHit" value="">
		<input type="hidden" name="bTitle" value="">
		<input type="hidden" name="bContent" value="">
		
		<table class="table table-bordered">
			<tr>  
				<th scope="col">번호</th>
				<td>  </td>
			</tr>
			<tr>
				<th scope="col">조회수</th>
				<td>  </td>
			</tr>
			<tr>
				<th scope="col">이름</th>
				<td> </td>
			</tr>
			<tr>
				<th scope="col">제목</th>
				<td></td>
			</tr>
			<tr>
				<th scope="col">내용</th>
				<td> 
					<p></p>
				</td>
			</tr>
			<tr>
				<td colspan="2"> 
					<input type="submit" value="수정"> &nbsp;&nbsp; 
					<a href="boardList.jsp">목록보기</a> &nbsp;&nbsp; 
					<a href="delete.jsp?bId=${content_view.bId}">삭제</a> &nbsp;&nbsp; 
				</td>
			</tr>
		</table>
	</form>
	
	<!-- 부트스트랩 자바스크립트 -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

 

delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

 

modifyCheck.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

 

modifyForm.jsp

<%@page import="com.jsp.board.BoardDTO"%>
<%@page import="com.jsp.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<!-- 부트스트랩 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<style type="text/css">
	table{
		width : 50% !important;
		margin-left:25%; 
    	margin-right:25%;
		
	}
</style>

</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
	%>
	
	<%--
		넘어온 파라미터를 EL param 객체로 채우기
	 --%>

	
	<br><h1 style="text-align: center;">게시글 수정</h1><br>
	
	<form action="modifyCheck.jsp" method="post" accept-charset="UTF-8">
		<input type="hidden" name="bId" value="">
		<table class="table table-bordered">
			<tr> 
				<th scope="col">번호</th>
				<td> </td>
			</tr>
			
			<tr>
				<th scope="col">조회수</th>
				<td> </td>
			</tr>
			
			<tr>
				<th scope="col">이름</th>
				<td> <input type="text" name="bName" value=""></td>
			</tr>
			
			<tr>
				<th scope="col">제목</th>
				<td> <input type="text" name="bTitle" value=""></td>
			</tr>
			
			<tr>
				<th scope="col">내용</th>
				<td> 
					<textarea rows="10" cols="30" name="bContent" ></textarea>
				</td>
			</tr>
			
			<tr>
				<td colspan="2"> 
					<a href="boardList.jsp">목록보기</a> &nbsp;&nbsp;&nbsp;&nbsp;
					<input type="submit" value="수정"> 
				</td>
			</tr>
			
		</table>
	</form>
	
	<!-- 부트스트랩 자바스크립트 -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

 

writeCheck.jsp

<%@page import="com.jsp.board.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<%--
		1. 넘어온 데이터 받기
		2. DAO 객체 생성하기
		3. write 메소드 호출 후 결과값 얻기
		4. 결과값을 얻은 후에 로직 처리하기 
		  (boardList.jsp로 이동하기)
	 --%>
	
	<%
		request.setCharacterEncoding("UTF-8");
		
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		
		BoardDAO dao = BoardDAO.getInstance();
		
		int result = dao.write(bName, bTitle, bContent);
	
		if(result == 1){
	%>
			<script>
				alert('글이 등록되었습니다.');
				window.location = 'boardList.jsp';
			</script>
	
	<%
		}else{
	%>
			<script>
				alert('글이 등록되지 않았습니다.');
				window.location = 'boardList.jsp';
			</script>
	<%
		}
	%>
	
	
</body>
</html>

 

writeForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<!-- 부트스트랩 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<style type="text/css">
	table{
		width : 50% !important;
		margin-left:25%; 
    	margin-right:25%;
		
	}
</style>
</head>
<body>
	
	<br><h1 style="text-align: center;">게시글 작성</h1><br>
	
	<form action="writeCheck.jsp" method="post" accept-charset="UTF-8" >
		<table class="table table-bordered">
			<tr>
				<th scope="col">이름</th>
				<td> <input type="text" name="bName" size="30"> </td>
			</tr>
			<tr>
				<th scope="col">제목</th>
				<td> <input type="text" name="bTitle" size="30"> </td>
			</tr>
			<tr>
				<th scope="col">내용</th>
				<td> <textarea name="bContent" rows="10" cols="40" ></textarea> </td>
			</tr>
			<tr >
				<td colspan="2"> 
					<input type="submit" value="입력"> &nbsp;&nbsp; 
					<a href="boardList.jsp">목록보기</a>
				</td>
			</tr>
		</table>
	</form>

	<!-- 부트스트랩 자바스크립트 -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</body>
</html>
반응형

'강의 > JSP 강의 정리' 카테고리의 다른 글

JSP 강의 정리 20일차  (0) 2022.08.02
JSP 강의 정리 18일차  (0) 2022.07.29
JSP 강의 정리 17일차  (0) 2022.07.28
JSP 강의 정리 16일차  (0) 2022.07.27
JSP 강의 정리 15일차  (0) 2022.07.26