JAVA/JSP 프로그래밍

[JSP] 간단한 게시판 만들어 보기

미로910 2024. 7. 8. 14:40
create database demo6;
use demo6;

create table posts(
	id int auto_increment primary key, 
    title varchar(255) not null, 
    content text not null,
    created_at timestamp default current_timestamp
);

select * from posts;

DB 설정

com/tenco/servelet/DBUtil.java 파일 생성
package com.tenco.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {

	private static final String URL = "jdbc:mysql://localhost:3306/demo6?serverTimezone=Asia/Seoul";
	private static final String USER = "root";
	private static final String PASSWORD = "asd123";
	
	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		
		Class.forName("com.mysql.cj.jdbc.Driver");
		return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
}

 

webapp/createPost.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/styles.css">
</head>
<body>
	<h2>게시글 작성</h2>
	<form action="create-post" method="post">
		<label for="title">제목 : </label>
		<input type="text" id="title" name="title" value="게시글 제목 1">
		<br><br>
		<label for="content">내용 : </label>
		<input type="text" id="content" name="content" value="JSP 웹 프로그래밍 ....">
		<button type="submit">글 작성</button>
	</form>
	<br>
	<a href="read-posts">게시글 목록</a>
</body>
</html>

com.tenco.servlet/CreatePostServlet.java 파일 생성
package com.tenco.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/create-post")
public class CreatePostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public CreatePostServlet() {
        super();
    }

    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 기본 값 설정 (언어 설정)
		request.setCharacterEncoding("UTF-8");
		
		// HTTP 요청 메시지에서 데이터 추출
		String title =  request.getParameter("title");
		String content = request.getParameter("content");

		// 인증 검사 생략(로그인 여부 확인)
		// 데이터 유효성 검사는 생략 ....
		
		try (Connection conn = DBUtil.getConnection()){
			
			String sql = "INSERT INTO posts(title, content) VALUES (?,?)" ;
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, title);
			pstmt.setString(2, content);
			pstmt.executeUpdate();
			response.sendRedirect("result.jsp?message=create-sucess");
			
			
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("result.jsp?message=error");
		}
	}

}

 

result.jsp 파일 생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>결과 확인 페이지</title>
</head>
<body>
	<h2>결과 확인 페이지</h2>
	<%
		String message = request.getParameter("message");
		if("create-sucess".equals(message)) {
			out.println("<p>게시글 작성에 성공</p>");
		} else {
			out.println("<p>작성에 실패</p>");
		}
	%>
	<br>
	<%-- 게시글 작성 화면으로 이동 --%>
	<a href="createPost.jsp">게시글 작성 페이지</a>
	<%-- 게시글 목록 화면으로 이동 --%>
	<a href="read-posts">게시글 리스트 페이지</a>
</body>
</html>

 

삭제 버튼을 누르면 삭제가 될 수 있게 기능 만들기

게시글 삭제 기능 - DeletePostServlet.java 생성
package com.tenco.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/delete-post")
public class DeletePostServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    public DeletePostServlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("boardId");
        System.out.println("id : " + id);
    }

}

readPosts.jsp
<%@page import="java.sql.ResultSet"%>
<%@ 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/style.css">
</head>
<body>
	<h2>게시글 목록</h2>
	<%
		ResultSet rs = (ResultSet) request.getAttribute("resultSet");
		if(rs != null) {
	%>	
		<table border="1">
			<tr>
				<th>ID</th>
				<th>제목</th>
				<th>작성일</th>
				<th></th>
			</tr>
			<%
				while(rs.next()){
					
				
			
			%>
			<tr>
				<td><%= rs.getInt("id") %></td>
				<td><%= rs.getString("title") %></td>
				<td><%= rs.getString("content") %></td>
				<td><%= rs.getString("created_at") %></td>
				<td>
					<form action="delete-post" method="get">
						<input type="hidden" name="boardId" value="<%= rs.getInt("id") %>">
						<button type="submit">삭제</button>
					</form>
				</td>
			</tr>
			<% } %>
		</table>
	<% 	} else { %>
		<p> 작성된 게시글 하나도 없습니다. </p>	
	<%  } %>
	
</body>
</html>

package com.tenco.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/delete-post")
public class DeletePostServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    public DeletePostServlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("boardId");
        System.out.println("id : " + id);
        
        try (Connection conn = DBUtil.getConnection()){
			
        	String sql = " DELETE FROM posts WHERE id = ? ";
        	PreparedStatement pstmt = conn.prepareStatement(sql);
        	pstmt.setInt(1, Integer.parseInt(id));
        	pstmt.executeUpdate();
        	
        	// 클라이언트에게 새로운 URL를 자동으로 요청하도록 HTTP 응답을 보낸다
        	// HTTP 상태 코드 302(임시 이동) 사용자에게 새로운 URL로 이동처리 시킨다
        	response.sendRedirect("result.jsp?message=delete-success");
        	
        	
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("result.jsp?message=error");
		}
    }

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>결과 확인 페이지</title>
</head>
<body>
	<h2>결과 확인 페이지</h2>
	<%
		String message = request.getParameter("message");
		if("create-sucess".equals(message)) {
			out.println("<p>게시글 작성에 성공</p>");
		} else if("delete-success".equals(message)){
			out.println("<p>게시글 삭제에 성공</p>");
		} else {
			out.println("<p>작성에 실패</p>");
		}
	%>
	<br>
	<%-- 게시글 작성 화면으로 이동 --%>
	<a href="createPost.jsp">게시글 작성 페이지</a>
	<%-- 게시글 목록 화면으로 이동 --%>
	<a href="read-posts">게시글 리스트 페이지</a>
</body>
</html>

else if("delete-success".equals(message)){

out.println("<p>게시글 삭제에 성공</p>");

수정하기

삭제 버튼 누르면 게시글 삭제 성공이 완료

package com.tenco.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/update-post")
public class UpdatePostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public UpdatePostServlet() {
		super();

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		// 일반적인 로직 수정 - 권한확인 확인(세션정보, 작성자 정보 비교)
		String id = request.getParameter("boardId");
		// SELECT * FROM posts where id = 3; <-- 작성자
		// 유효성 검사 (사용자 새로 입력 정보가 유효성 검사)
		
		// Update 구문 처리
		// 트랜잭션 처리를 해야 한다 (commit, rollback)
		
		
		
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		
		try (Connection con = DBUtil.getConnection()) {
			String sql = "UPDATE posts SET title = ?, content = ? WHERE id = ? ";
			PreparedStatement pstmt =  con.prepareStatement(sql);
			pstmt.setString(1, title);
			pstmt.setString(2, content);
			pstmt.setInt(3, Integer.parseInt(id));
			pstmt.executeUpdate();
			response.sendRedirect("result.jsp?message=update-success");
			
			
		} catch (Exception e) {
			response.sendRedirect("result.jsp?message=error");

		}
		
		
		
	}

}
<%@page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시글 상세보기 화면</title>
</head>
<body>
	<h2>상세보기 화면</h2>
	<%
		ResultSet rs = (ResultSet) request.getAttribute("resultSet");
		if(rs.next()) {
	%>
		<h3> <%= rs.getString("title") %></h3>
		<p><%= rs.getString("content") %> </p>
		<p><small> 작성일 : <%= rs.getString("created_at") %></small></p>
		<br><br>
		<!--  수정 폼   -->
		<h3>게시글 수정</h3>
		<form action="update-post" method="post">
			<input type="hidden" name="boardId" value="<%= rs.getInt("id") %>">
			<label for="title">제목 : </label>
			<input type="text" id="title" name="title" value=" <%= rs.getString("title") %>">
			<br><br>
			<label for="content">내용 : </label>
			<input type="text" id="content" name="content" value=" <%= rs.getString("content") %>">
			<br><br>
			<button type="submit">수정하기</button>
		</form>		
		
	<%		
		}
	%>
</body>
</html>

수정이 된 걸 확인할 수 있다

SQL에서도 수정된 것을 확인할 수 있다