• 티스토리 홈
  • 프로필사진
    Song hyun
  • 방명록
  • 공지사항
  • 태그
  • 블로그 관리
  • 글 작성
Song hyun
  • 프로필사진
    Song hyun
    • 분류 전체보기 (780)
      • 백준 (0)
      • 일본어 (0)
        • 모모타로TMC (0)
      • 영어 (2)
        • Diary (0)
        • Toast Masters (2)
      • 메모 (13)
      • 설치 메뉴얼 (30)
      • Java (178)
      • MySQL (60)
      • JSP (67)
      • Springboot (46)
      • HTML,CSS, JS (71)
        • HTML (8)
        • CSS (12)
        • JavaScript (37)
        • HTML&CSS 스터디 (13)
      • C++ (7)
      • Linux (7)
      • JPA (34)
      • Kotlin (2)
      • Flutter (42)
      • Error Note (39)
      • 디자인 패턴 (12)
      • 디지털논리회로 (4)
      • 데이터베이스 시스템 (8)
      • 알고리즘 (7)
      • 운영체제 (3)
      • 이산수학 (3)
      • 인공지능 (1)
      • 자료 구조 (14)
        • 기본 개념 (14)
        • 자료구조 스터디 (0)
      • 💡My project (76)
        • 팩맨 : Java Swing 게임 제작 프로젝트 (6)
        • 네이트톡 : Java 소켓 통신 프로젝트 (4)
        • 포켓옥션 : HikariCP&JDBC CRUD 프.. (3)
        • 이지 부산 : BDIA-Devton 2024 프로.. (20)
        • 그린 유니버시티 : JSP를 사용한 학사관리 프로.. (1)
        • 애드 포커 : 웹 소켓과 Spring을 사용한 카.. (1)
        • 셸위 : 게임 친구 매칭 사이트 (21)
        • 다모아 : 개발자 중개 플랫폼 (20)
      • 📗스터디 (13)
        • CNN : 웹개발 스터디 (10)
        • Node&React로 유튜브 사이트 만들기 (3)
      • 📙독서 및 강연 기록 (36)
        • 강연 (14)
        • 독서 (22)
  • 방문자 수
    • 전체:
    • 오늘:
    • 어제:
  • 최근 댓글
      등록된 댓글이 없습니다.
    • 최근 공지
        등록된 공지가 없습니다.
      # Home
      # 공지사항
      #
      # 태그
      # 검색결과
      # 방명록
      • [JSP] 15. 서블릿과 DB 연동
        2024년 07월 03일
        • Song hyun
        • 작성자
        • 2024.07.03.:50
        728x90
        반응형

        [JSP] 15. 서블릿과 DB 연동

         

        *form 태그: 서버로 데이터를 전송하는 태그!

        *form-action

        *상대 경로와 절대 경로

         

        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>Todo Form</title>
        </head>
        <body>
        	
        	<div class="todo-form">
        		<h2>ADD Todo</h2>
        		<form action="">
        			<label for="title">Title : </label>
        			<input type="text" id="title" placeholder="Enter todo title">
        			<label for="description">Description : </label>
        			<input type="text" id="description" placeholder="Enter todo description">
        			<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);
        	}
        
        }
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>Todo Form</title>
        </head>
        <body>
        	<!-- form 태그에서 데이터를 서버로 제출할 때, 만드시 name 속성이 있어야 한다. -->
        	<div class="todo-form">
        		<h2>ADD Todo</h2>
        		<!-- 절대 경로 -->
        		<!-- / 부터 시작한다면 절대 경로를 의미하고, context-root부터 시작이다. -->
        		<!-- 상대 경로 -->
        		<form action="http://localhost:8080/s02/todo-insert" method="post">
        			<label for="title">Title : </label>
        			<input type="text" id="title" placeholder="Enter todo title" name="title">
        			<label for="description">Description : </label>
        			<input type="text" id="description" placeholder="Enter todo description" name="description" value="html 연습">
        			<button type="submit"> Save </button>
        		</form>
        	</div>
        	
        </body>
        </html>

         

        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,
            creadted_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;
        		cursor:pointer;
        		border-radius:4px;
        		border: none;
        	}
        	
        </style>
        </head>
        <body>
        	<!-- form 태그에서 데이터를 서버로 제출할 때, 만드시 name 속성이 있어야 한다. -->
        	<div class="todo-form">
        		<h2>ADD Todo</h2>
        		<p>http://localhost:8080/s02/todo-add.html</p>
        		<!-- 절대 경로 -->
        		<!-- / 부터 시작한다면 절대 경로를 의미하고, context-root부터 시작이다. -->
        		<!-- 상대 경로 -->
        		<form action="http://localhost:8080/s02/todo-insert" method="post">
        			<label for="title">Title : </label>
        			<input type="text" id="title" placeholder="Enter todo title" name="title">
        			<label for="description">Description : </label>
        			<input type="text" id="description" placeholder="Enter todo description" 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.DriverManager;
        import java.sql.PreparedStatement;
        
        // 주소 설계 - 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) {
        			e.printStackTrace();
        		}
            }
        
        
        	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 {
        		
        		// 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) {
        			e.printStackTrace();
        			response.getWriter().print("Error : "+e.getMessage());
        			return;
        		}
        		
        		response.getWriter().println("Todo added successfully");
        	}
        
        }
        728x90
        반응형

        'JSP' 카테고리의 다른 글

        [JSP] 17. 서블릿 필터와 리스너  (0) 2024.07.03
        [JSP] 16.server.xml과 context.xml, web.xml  (0) 2024.07.03
        [JSP] 14. 서블릿과 서블릿 컨텍스트  (0) 2024.07.03
        [JSP] 13. 쿼리 스트링  (0) 2024.07.03
        [JSP] 12. URI와 URL  (0) 2024.07.03
        다음글
        다음 글이 없습니다.
        이전글
        이전 글이 없습니다.
        댓글
      조회된 결과가 없습니다.
      스킨 업데이트 안내
      현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
      ("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)
      목차
      표시할 목차가 없습니다.
        • 안녕하세요
        • 감사해요
        • 잘있어요

        티스토리툴바