Eclipse에서 Dynamic Web Project를 사용하고 MySQL을 연동한 게시판 예졔 보여줘.
ChatGPT의 말:
아래는 Eclipse에서 Dynamic Web Project + MySQL 연동을 이용해 간단한 게시판 예제를 만드는 방법입니다. 글 목록 보기, 글 작성 기능을 포함합니다.
🧩 기술 스택
- Eclipse (Dynamic Web Project)
- JSP + Servlet
- JDBC (MySQL 연동)
- MySQL
🧱 1. Eclipse에서 Dynamic Web Project 생성
✅ 1. 단계
- Eclipse 실행
- 상단 메뉴: File → New → Dynamic Web Project
- 프로젝트 이름: BoardMySQL
- Target Runtime: Tomcat 선택 (없다면 "New Runtime"으로 추가)
- Dynamic Web Module version: 3.1 또는 4.0
- Configuration: 기본값 사용
- Finish
🧩 2. 프로젝트 폴더 구조 정리
src/main/java가 없더라도 기본 src 디렉토리를 사용할 수 있습니다.
구조 예시
BoardMySQL/
├── Java Resources/
│ └── src/
│ ├── controller/
│ ├── dao/
│ └── model/
├── WebContent/
│ ├── index.jsp
│ ├── list.jsp
│ ├── write.jsp
│ └── WEB-INF/
│ └── web.xml
└── lib/
└── mysql-connector-j-8.x.x.jar
src 우클릭 → New → Package 로 controller, dao, model 폴더 생성
⚙️ 3. MySQL JDBC 드라이버 추가
방법:
- MySQL Connector/J에서 .jar 다운로드
- BoardMySQL/lib 폴더에 .jar 복사
- Eclipse에서:
- 프로젝트 우클릭 → Build Path → Configure Build Path
- Libraries 탭 → Add JARs... 선택 → 위 파일 추가
🔧 4. MySQL 연동 설정
DB 생성
CREATE DATABASE boarddb;
USE boarddb;
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
✍️ 5. JSP/Servlet/DAO 코드 작성
Post.java (model)
package model;
import java.sql.Timestamp;
public class Post {
private int id;
private String title;
private String content;
private Timestamp createdAt;
public Post(int id, String title, String content, Timestamp createdAt) {
this.id = id;
this.title = title;
this.content = content;
this.createdAt = createdAt;
}
public int getId() { return id; }
public String getTitle() { return title; }
public String getContent() { return content; }
public Timestamp getCreatedAt() { return createdAt; }
}
BoardDAO.java (dao)
package dao;
import model.Post;
import java.sql.*;
import java.util.*;
public class BoardDAO {
private static final String URL = "jdbc:mysql://localhost:3306/boarddb?useSSL=false&serverTimezone=Asia/Seoul";
private static final String USER = "root"; // 본인 DB 계정
private static final String PASSWORD = "본인 DB 비밀번호";
private Connection getConn() throws SQLException {
//return DriverManager.getConnection(URL, USER, PASSWORD)
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver"); // Use the appropriate driver class name
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace(); // Handle any exceptions
}
return null;
}
public List<Post> getAllPosts() {
List<Post> list = new ArrayList<>();
String sql = "SELECT * FROM posts ORDER BY id DESC";
try (Connection conn = getConn();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
list.add(new Post(
rs.getInt("id"),
rs.getString("title"),
rs.getString("content"),
rs.getTimestamp("created_at") // ← created_at 추가
));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public void addPost(String title, String content) {
String sql = "INSERT INTO posts (title, content) VALUES (?, ?)";
try (Connection conn = getConn();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
BoardServlet.java (controller)
package controller;
import dao.BoardDAO;
import model.Post;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
@WebServlet("/board")
public class BoardServlet extends HttpServlet {
private BoardDAO dao = new BoardDAO();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if ("write".equals(action)) {
request.getRequestDispatcher("write.jsp").forward(request, response);
} else {
List<Post> posts = dao.getAllPosts();
request.setAttribute("posts", posts);
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("title");
String content = request.getParameter("content");
dao.addPost(title, content);
response.sendRedirect("board");
}
}
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*, model.Post" %>
<%
List<Post> posts = (List<Post>) request.getAttribute("posts");
%>
<html>
<head>
<title>게시판</title>
</head>
<body>
<h1>게시판</h1>
<a href="board?action=write">글쓰기</a>
<hr>
<ul>
<% for (Post post : posts) { %>
<li>
<strong><%= post.getTitle() %></strong><br/>
<pre><%= post.getContent() %></pre>
<small>작성일: <%= post.getCreatedAt() %></small>
<hr>
</li>
<% } %>
</ul>
</body>
</html>
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>글쓰기</title>
</head>
<body>
<h1>글 작성</h1>
<form action="board" method="post">
제목: <input type="text" name="title" required><br>
내용:<br>
<textarea name="content" rows="5" cols="40" required></textarea><br>
<button type="submit">등록</button>
</form>
<a href="board">목록으로</a>
</body>
</html>
index.jsp
<% response.sendRedirect("board"); %>
🌐 6. web.xml 설정 (필요 시)
보통 @WebServlet("/board")을 사용하므로 생략 가능하지만, 다음처럼 기본 index.jsp를 설정하세요:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<display-name>BoardMySQL</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
▶️ 7. 실행
- Tomcat 실행: Eclipse → Servers → Tomcat 시작
- 브라우저에서 열기:
http://localhost:8080/BoardMySQL/
'전자정부 프레임워크 공부' 카테고리의 다른 글
게시판 페이지네이션 기능 구현 [전자정부 프레임워크 공부] (0) | 2025.05.18 |
---|---|
게시판 개발용 페이크 데이터 추가하기 [전자정부 프레임워크 공부] (0) | 2025.05.18 |
Eclipse에서 Dynamic Web Project 기본 예제 [전자정부 프레임워크 공부] (1) | 2025.05.18 |
Java 기본 문법 [전자정부 프레임워크 공부] (0) | 2025.05.18 |
WAS란? [전자정부 프레임워크] (0) | 2025.05.16 |