본문 바로가기
개발 공부 Today I Learned

[국비 29일차 TIL] 게시판 만들기 2 (글 저장, 글 수정)

by 개발자신입 2024. 1. 2.
반응형

 

 

MariaDB 

INSERT INTO board (board_title, board_content, board_write) 
VALUES ('test','test','test');

SELECT * FROM board ORDER BY board_no DESC LIMIT 0, 10;

# 데이터베이스에서의 if문 
# if(조건, TRUE, FALSE)

NOW() #현재 시간 보여줌.
DATE_FORMAT(date, format[, locale]) #날짜를 뒤의 형태로 변경해서 보여줌


SELECT board_date FROM board

-- 년 월 일
-- 시 분 초
SELECT DATE_FORMAT(NOW(), '%Y-%M-%D') FROM DUAL; -- 2024-January-2nd
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d') FROM DUAL; -- 2024-01-02

SELECT DATE_FORMAT(NOW(), '%H-%I-%S') FROM DUAL; -- 대문자H (24시간)
SELECT DATE_FORMAT(NOW(), '%h-%i-%s') FROM DUAL; -- 소문자h (12시간)

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %h:%i:%s') FROM DUAL;


SELECT DATE_FORMAT(board_date, '%Y-%m-%d %h:%i:%s') FROM board;


-- 번호, 제목, 글쓴이, 조회수 + 정렬(역순) + 10개씩 

CREATE VIEW boardview AS -- view 생성 명령어
SELECT 
board_no, board_title, board_write,
if(
	DATE_FORMAT(NOW(), '%Y-%m-%d') = DATE_FORMAT(board_date, '%Y-%m-%d'),
	DATE_FORMAT(board_date, '%h:%i'), -- true면  시:분
	DATE_FORMAT(board_date, '%m-%d')  -- false면 월-일
	) AS board_date,  board_count
FROM board 
ORDER BY board_no DESC  -- 역순 정렬
LIMIT 0, 10;			-- 10개씩

DROP VIEW boardview;

SELECT * FROM boardview;

UPDATE board SET board_title='변경',
			 	 board_content='내용 변경'
				 WHERE board_no=15

 


index.jsp

 

<%@page import="com.coffee.dao.BoardDAO"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ 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>
<style type="text/css">
table{
	width: 800px;
	border-collapse: collapse;
}
td {
	text-align: center;
	border-bottom: dotted gray 1px;
}
tbody tr:hover {
	background-color: #A77EEB;
}

.w1 {
	width: 10%;
}
.w2 {
	width: 15%;
}
.w5 {
	width: 25%;
	text-align: left;
}
tr{
	height: 40px;
}

</style>

<script src="./js/write.js" charset="UTF-8"></script>

</head>
<body>
	<h1>index</h1>
	<!-- 게시판 내용 보기 -->
	<%
	BoardDAO dao = new BoardDAO();
	List<Map<String, Object>> list = dao.boardList();
	%>

	<table>
		<thead>
			<tr>
				<th>번호</th>
				<th>제목</th>

				<th>글쓴이</th>
				<th>작성일</th>
				<th>조회수</th>
			</tr>
		</thead>
		<tbody>
		<%
		
		// servlet 서블릿 : 자바 코드 속에 html이 있음.
		// jsp java server page : html코드 속에 java가 있음.
		
		for(Map<String, Object> map : list) {
		%>
			<tr>
				<td class="w1"><%= map.get("board_no")%></td>
				<td class="w5">
					<a href="./detail.jsp?no=<%= map.get("board_no")%>">
					<%= map.get("board_title")%></a>
				</td>
				<td class="w1"><%= map.get("board_write")%></td>
				<td class="w2"><%= map.get("board_date")%></td>
				<td class="w1"><%= map.get("board_count")%></td>
				
			</tr>
		<% 
		} 
		%>		
		</tbody>
	
	</table>
	
	<button onclick="write1()">글쓰기</button>
	
<script type="text/javascript">

</script>
	
	<br><br>
	연습 <a href="./test">>>여기<<</a> TEST로 넘어가기 눌러주세요. <br><br>
	리스트 <a href="./detail.jsp">>>여기<<</a> 리스트로 넘어가기 눌러주세요.
	
	<!-- 
	자바 코드를 여러 줄 작성 < % % >
	자바의 값 하나 출력 < % = % >
	 -->
	
</body>
</html>

 

 

BoardDAO에서 글 저장 및 수정하기 파트

 

	// 글 저장하기 24.01.02
	
	public int write(String title, String content) {
		int result = 0;
		
		Connection con = dbCon.getConn();
		PreparedStatement pstmt = null;
		// resultSet 필요없음. 되돌아오는 값 없어서.
		String sql = "INSERT INTO board (board_title, board_content, board_write) VALUES (?,?,?)";
		String name = "커피"; // 나중에 세션에서 받아오기
		
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1,  title);
			pstmt.setString(2,  content);
			pstmt.setString(3,  name);
			
			result = pstmt.executeUpdate(); // 결과를 숫자로 되돌려줌 = 변경된 레코드 수
			/*
			 * execute();		실행, 참거짓(boolean) = update, insert, delete
			 * executeQuery();  실행, rs 			  = select
			 * executeUpdate(); 실행, 숫자(정수) 	  = update, insert, delete
			 */
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
		
		
		return result;
		
	}



// 글 수정하기
	public void update(String no, String title, String content) {
		Connection con = dbCon.getConn();
		PreparedStatement pstmt = null;
		String sql = "UPDATE board SET board_title=?, board_content=? WHERE board_no=?";
		
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, title);
			pstmt.setString(2, content);
			pstmt.setString(3, no);

			pstmt.execute();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
	}
}

 

write.jsp

 

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

<link rel="stylesheet" type="text/css" href="./css/write.css">

<script type="text/javascript"> // 제목,내용 없이 입력했을 때 경고창 팝업
	function check(){
		//alert('!');
		//var title = document.getElementsByName("title");
		//alert(title[0].value);
		
		var title = document.getElementById("title");
		// alert(title.value.length); 제목의 길이
		if (title.value.length < 5) {
			alert("제목은 5글자 이상이어야 합니다.");
			title.focus();
			return false;
		}
		

		var content = document.getElementsByClassName("content");
		//alert(content[0].value.length); // Elements : s가 붙으면 배열 요소
		if(content[0].value.length < 3) {
			alert("내용은 3글자 이상 작성해주세요.");
			content[0].focus();
			return false;
		}
		
		
	}
</script>

</head>
<body>
	<h1>글을 작성하는 페이지</h1>
	<!-- form 글 제목, 글 내용 -->
	<form action="./write" method="post"> <!-- get/post방식 -->
		<input type="text" name="title" id="title"><br>
		<textarea name="content" class="content"></textarea><br>
		<button type="submit" onclick="return check()">글쓰기</button>
	</form>
	
	

</body>
</html>

 

Write.java

 

package com.coffee.web;

import java.io.IOException;

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 com.coffee.dao.BoardDAO;

@WebServlet("/write")
public class Write extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Write() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		doGet(request, response);
		
		// post 메소드이기 때문에 post 항목에서 처리함.
		
		request.setCharacterEncoding("UTF-8");	// 한글 패치
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		
		BoardDAO dao = new BoardDAO();
		
		int result = dao.write(title, content);
		
		if(result == 1) {
			response.sendRedirect("./index.jsp");
		} else {
			response.sendRedirect("./error.jsp");
		}
	}

}

 

 

update.jsp

 

<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 수정하기 </title>

<link rel="stylesheet" type="text/css" href="./css/write.css">

<script type="text/javascript"> // 제목,내용 없이 입력했을 때 경고창 팝업
	function check(){
		var title = document.getElementById("title");
		if (title.value.length < 5) {
			alert("제목은 5글자 이상이어야 합니다.");
			title.focus();
			return false;
		}
		

		var content = document.getElementsByClassName("content");
		if(content[0].value.length < 3) {
			alert("내용은 3글자 이상 작성해주세요.");
			content[0].focus();
			return false;
		}
		
		
	}
</script>

</head>
<body>
<%
Map<String, Object> detail = (Map<String, Object>) request.getAttribute("detail");
%>
	<h1>글을 수정하는 페이지</h1>
	<form action="./update" method="post"> <!-- get/post방식 -->
		<input type="text" name="title" id="title" value="<%=detail.get("board_title")%>"><br>
		<textarea name="content" class="content"><%=detail.get("board_content")%></textarea><br>
		<button type="submit" onclick="return check()">수정하기</button>
		<input type="text" name="no" value="<%=detail.get("board_no")%>">
	</form>
	
	

</body>
</html>

 

Update.java

package com.coffee.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
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 com.coffee.dao.BoardDAO;

@WebServlet("/update")
public class Update extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Update() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// DAO 호출하기
		BoardDAO dao = new BoardDAO();
		// 날아오는 번호 잡기 ./update?no=**
		String no = request.getParameter("no");
		// 데이터베이스에 질의해서 레코드 1개 가져오기
		Map<String, Object> detail = dao.detail(no);
		// update.jsp에게 돌려주기 = 페이지 이동
//		System.out.println(detail);

		// update.jsp에 값 보내기
		request.setAttribute("detail", detail); 	// (변수명, 값)
		
		// jsp 부르기
		RequestDispatcher rd = request.getRequestDispatcher("update.jsp");
		rd.forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String title = request.getParameter("title");
		String no = request.getParameter("no");
		String content = request.getParameter("content");
		
//		System.out.println(title);
//		System.out.println(no);
//		System.out.println(content);
		
		BoardDAO dao = new BoardDAO();
		dao.update(no, title, content); 
		
		response.sendRedirect("./detail.jsp?no="+no);
		
	}

}

 

반응형

댓글