Java

2024.07.01 JSP 프로그래밍 기본 서블릿과 데이터베이스 연동

정훈5 2024. 7. 1. 15:04

class_servlet_02

todo-add.html

TodoServlet.java

class_38.sql

mysql-connector-java-8.0.21.jar 적용

class_38.sql
0.00MB

 

class_servlet_02.zip
2.17MB

학습 목표 

1. 서버로 데이터를 전송하는 form 태그 사용해 보자. 
2. form 태그 action 에서 상대경로 와 절대 경로 개념을 이해하자.

 

HTML 파일명은 어떤 규칙으로 작성해볼까?

 

하이픈을 사용한 케밥 표기법 (Kebab Case)

index.html
contact-us.html
user-profile.html
product-list.html

 

언더스코어를 사용한 스네이크 표기법 (Snake Case)

index.html
contact_us.html
user_profile.html
product_list.html

 

 

class_servlet_02 프로젝트 생성

webapp << todo-add.html 생성

src >>  com.tenco.controller 패키지 >> TodoServlet.java 생성

http://localhost:8080/s02/todo-add.html 으로 접속

 

webapp/todo-add.html 파일에 작성

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- form 태그에서 데이터를 서버로 제출할 때 반드시 name 속성이 있어야 한다. -->
	<div class="todo-form">
		<h2>ADD Todo</h2>
		
		<!--  절대 경로 -->
		<!--  /부터 시작한다면 절대 경로를 의미하고 context-root 부터 시작이다. -->
		<!--  http://내IP:포트번호/Context-root//todo-insert -->
		
		<!--  상대 경로 -->
		<!--   -->
		<!-- http://localhost:8080/s02/todo-add.html -->
		<form action="/s02/todo-insert" method="post">
			<label for="title">Title : </label>
			<input type="text" id="title" placeholder="Enter todo title" name="title" value = "코딩하기"> 
			<label for = "description">Description: </label> 
			<input type="text" id="description" placeholder="Enter todo title" name="description" value="html 연습"> 
			<button type="submit"></button>
		</form>
	</div>

</body>
</html>

 

TodoServlet 파일(서블릿 클래스 생성)

package com.tenco.controller;

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;

// 주소 설계 - http:localhost:8080/s02/todo-insert
@WebServlet("/todo-insert")
public class TodoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public TodoServlet() {
        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 {
		System.out.println("TODO-INSERT POST 호출 됨");
		
		// HTTP 메세지에서 데이터 추출하기 
		// form 태그에서 name 속성이 있어야 한다.
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		
		System.out.println("title : " + title);
		System.out.println("description : " + description);
		
	}
}

 

 


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Todo Form</title>

<style type="text/css">
	
	body {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		margin: 0;
		font-family: arial, sans-serif;
		background-color: #f4f4f4;
	}
	
	.todo-form {
		background-color: #fff;
		padding: 20px;
		border-radius: 8px;
		width: 400px;
		box-shadow: 0 0 10px rgba(0,0,0,0.1);
	}
	
	form {
		display: flex;
		flex-direction: column;
	}
	
	label {
		margin-bottom : 5px;
		font-weight: bold;
	}
	
	input[type = "text"] {
		margin-bottom: 15px;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
		
	}
	
	button {
		padding: 10px;
		background-color: #28a745;
		color: white;
		border: none;
		cursor: pointer;
		border-radius: 4px;
	}
	
</style>

</head>
<body>

	<!-- form 태그에서 데이터를 서버로 제출할 때 반드시 name 속성이 있어야 한다. -->
	<div class="todo-form">
		<h2>ADD Todo</h2>
		<p>http://localhost:8080/s02/todo-add.html</p>
		<!--  절대 경로 -->
		<!--  /부터 시작한다면 절대 경로를 의미하고 context-root 부터 시작이다. -->
		<!--  http://내IP:포트번호/Context-root//todo-insert -->
		
		<!--  상대 경로 -->
		<!--   -->
		<!-- http://localhost:8080/s02/todo-add.html -->
		<form action="/s02/todo-insert" method="post">
			<label for="title">Title : </label>
			<input type="text" id="title" placeholder="Enter todo title" name="title" value = "코딩하기"> 
			<label for = "description">Description: </label> 
			<input type="text" id="description" placeholder="Enter todo title" name="description" value="html 연습"> 
			<button type="submit">save</button>
		</form>
	</div>

</body>
</html>

 

 

 

package com.tenco.controller;

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;

// 주소 설계 - http:localhost:8080/s02/todo-insert
@WebServlet("/todo-insert")
public class TodoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public TodoServlet() {
        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 {
		System.out.println("TODO-INSERT POST 호출 됨");
		
		// HTTP 메세지에서 데이터 추출하기 
		// form 태그에서 name 속성이 있어야 한다.
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		
		System.out.println("title : " + title);
		System.out.println("description : " + description);
		
	}
}

 


DB 생성 및 테이블 설계

create database db_todo;
use db_todo; 

-- 테이블 생성 
create table tb_todo(
	id int auto_increment primary key, 
  title varchar(255) not null, 
  description text not null, 
  completed boolean not null default false, 
  created_at timestamp default current_timestamp
);

desc tb_todo;
select * from tb_todo;

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Todo Form</title>

<style type="text/css">
	
	body {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		margin: 0;
		font-family: arial, sans-serif;
		background-color: #f4f4f4;
	}
	
	.todo-form {
		background-color: #fff;
		padding: 20px;
		border-radius: 8px;
		width: 400px;
		box-shadow: 0 0 10px rgba(0,0,0,0.1);
	}
	
	form {
		display: flex;
		flex-direction: column;
	}
	
	label {
		margin-bottom : 5px;
		font-weight: bold;
	}
	
	input[type = "text"] {
		margin-bottom: 15px;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
		
	}
	
	button {
		padding: 10px;
		background-color: #28a745;
		color: white;
		border: none;
		cursor: pointer;
		border-radius: 4px;
	}
	
</style>

</head>
<body>

	<!-- form 태그에서 데이터를 서버로 제출할 때 반드시 name 속성이 있어야 한다. -->
	<div class="todo-form">
		<h2>ADD Todo</h2>
		<p>http://localhost:8080/s02/todo-add.html</p>
		<!--  절대 경로 -->
		<!--  /부터 시작한다면 절대 경로를 의미하고 context-root 부터 시작이다. -->
		<!--  http://내IP:포트번호/Context-root//todo-insert -->
		
		<!--  상대 경로 -->
		<!--   -->
		<!-- http://localhost:8080/s02/todo-add.html -->
		<form action="/s02/todo-insert" method="post">
			<label for="title">Title : </label>
			<input type="text" id="title" placeholder="Enter todo title" name="title" value = "코딩하기"> 
			<label for = "description">Description: </label> 
			<input type="text" id="description" placeholder="Enter todo title" name="description" value="html 연습"> 
			<button type="submit">save</button>
		</form>
	</div>

</body>
</html>

 

package com.tenco.controller;

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.ConnectionBuilder;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import com.mysql.cj.xdevapi.PreparableStatement;

// 주소 설계 - http:localhost:8080/s02/todo-insert
@WebServlet("/todo-insert")
public class TodoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public TodoServlet() {
        super();
    }
    
    // 정적 초기화 블록 - 단 한번 호출
    static {
    	try {
    		// JDBC 드라이버 로드 ( MySQL )
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	//
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("TODO-INSERT POST 호출 됨");
		
		// HTTP 메세지에서 데이터 추출하기 
		// form 태그에서 name 속성이 있어야 한다.
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		
		// 데이터 베이스 연동하는 코드를 작성해야 한다.
		String jdbcURL = "jdbc:mysql://localhost:3306/db_todo?serverTimezone=Asia/Seoul";
		String username = "root";
		String password = "asd123";
		
		String insertTodoSQL = " INSERT INTO tb_todo(title, description) values(?, ?) ";
		
		try(
			Connection conn = DriverManager.getConnection(jdbcURL, username, password);
			PreparedStatement pstmt = conn.prepareStatement(insertTodoSQL);
				) {
			pstmt.setString(1, "title");
			pstmt.setString(2, "description");
			int rowCount = pstmt.executeUpdate();
			System.out.println("rowCount : " + rowCount);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			response.getWriter().print("ERROR : " + e.getMessage());
			return;
		}
		
		response.getWriter().println(" Todo added successfully ");
		
	}
}