JSP - 06 (DB연동, 게시판만들기)

월요일좋아·2022년 10월 28일
0

JSP

목록 보기
6/9
post-thumbnail

Statement 객체

  • 정적인 쿼리에 사용
  • 하나의 쿼리를 사용하고 나면 더는 사용할 수 없음
  • 하나의 쿼리를 끝내면 close( )를 사용하여 객체를 즉시 해제해야 함
  • close( )를 사용하여 객체를 즉시 해제하지 않으면 무시할 수 없는 공간이 필요하며 페이지가 다른 작업을 수행하는 동안 멈추지 않기 때문(메모리를 많이 잡아먹음)
  • 복잡하지 않은 간단한 쿼리문을 사용하는 경우에 좋음
  • Statement 객체의 메소드 종류
    • executeQuery() 메소드로 데이터 조회하기
    • executeQuery() 메소드 사용 예
    • close() 해야되는 순서 : rs, stmt, conn
  • executeUpdate() 메소드로 데이터 삽입, 수정, 삭제하기
    • executeUpdate( ) 메소드는 INSERT, UPDATE, DELETE 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용
    • executeUpdate() 메소드 사용 예(INSERT)
    • executeUpdate() 메소드 사용 예(UPDATE)
    • executeUpdate() 메소드 사용 예(DELETE)

JDBC - DB 사용 예제

dbconn.jsp

<%-- dbconn--%>

<%@ page import="java.sql.*" %>
<%
    Connection conn = null;

    String url = "jdbc:mysql://localhost:3306/javadb";
    String user = "test1";
    String passwd = "java505";

    Class.forName("com.mysql.cj.jdbc.Driver");
    conn = DriverManager.getConnection(url, user, passwd);
%>

insert02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>
  <title>DB 사용하기</title>
</head>
<body>
<form action="insert02_process.jsp" method="post">
  <label for="user-id">아이디 : </label>
  <input type="text" id="user-id" name="userId"><br>
  <label for="user-pw">비밀번호 : </label>
  <input type="text" id="user-pw" name="userPw"><br>
  <label for="user-name">이름 : </label>
  <input type="text" id="user-name" name="userName"><br>
  <button type="submit">전송</button>
</form>
</body>
</html>

insert02_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Stack" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<%
  request.setCharacterEncoding("UTF-8");

  String userId = request.getParameter("userId");
  String userPw = request.getParameter("userPw");
  String userNm = request.getParameter("userName");

  Statement stmt = null;
  try {
    String sql = "INSERT INTO member (id, passwd, name)";
    sql += "Values ('" + userId + "', '" + userPw + "', '" + userNm + "') ";

    stmt = conn.createStatement();
    stmt.executeUpdate(sql);
    out.println("member 테이블에 데이터를 추가하였습니다.");
  }
  catch (SQLException e) {
    out.print("member 테이블에 데이터 추가를 실패하였습니다.");
    out.print("SQLException : " + e.getMessage());
  }
  finally {
    if (stmt != null) {
      stmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }
%>

</body>
</html>

PreparedStatement 객체

  • 동적인 쿼리에 사용
  • 하나의 객체를 여러 번 실행 할 수 있음.
  • 동일한 쿼리문에서 특정 값만 바꾸어서 여러 번 실행해야 될때, 매개변수가 많아서 쿼리문을 정리해야될 때 사용
  • setXxx() 메소드의 종류

PreparedStatement 객체의 메소드 종류

executeQuery() 메소드

데이터 조회

  • executeQuery( ) 메소드는 동적인 SELECT 쿼리문을 통해 데이터를 검색하는 데 사용
  • executeQuery( ) 메소드 사용 예 (SELECT)

executeUpdate( ) 메소드

INSERT, UPDATE, DELETE 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용

  • executeUpdate( ) 메소드 사용 예(INSERT)

PreparedStatement 객체 사용 예제 1

dbconn.jsp

<%-- dbconn--%>

<%@ page import="java.sql.*" %>
<%
    Connection conn = null;

    String url = "jdbc:mysql://localhost:3306/javadb";
    String user = "test1";
    String passwd = "java505";

    Class.forName("com.mysql.cj.jdbc.Driver");
    conn = DriverManager.getConnection(url, user, passwd);
%>

insert03.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - PreparedStatement</title>
</head>
<body>
<form action="insert03_process.jsp" method="post">
  <label for="user-id">아이디 : </label>
  <input type="text" id="user-id" name="userId"><br>
  <label for="user-pw">비밀번호 : </label>
  <input type="text" id="user-pw" name="userPw"><br>
  <label for="user-name">이름 : </label>
  <input type="text" id="user-name" name="userName"><br>
  <button type="submit">전송</button>
</form>
</body>
</html>

insert03_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - PreparedStatement</title>
</head>
<body>
<%@ include file="dbconn.jsp" %>
<%
  request.setCharacterEncoding("UTF-8");

  String userId = request.getParameter("userId");
  String userPw = request.getParameter("userPw");
  String userNm = request.getParameter("userName");

  PreparedStatement pstmt = null;

  try {
//    쿼리문 쓸때는 끝에 띄어쓰기 1칸 해주기! 습관들이자!
    String sql = "INSERT INTO member (id, passwd, name) ";
    sql += "VALUES (?, ?, ?) ";

    pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, userId);
    pstmt.setString(2, userPw);
    pstmt.setString(3, userNm);
    pstmt.executeUpdate();
    out.println("member 테이블에 데이터를 추가하였습니다.");
  }
  catch (SQLException e) {
    out.println("member 테이블에 데이터 추가를 실패했습니다.");
    out.println("SQLException : " + e.getMessage());
  }
  finally {
    if (pstmt != null) {
      pstmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }
%>
</body>
</html>

ResultSet 객체

  • Statement 또는 PreparedStatement 객체로 SELECT 문을 사용하여 얻어온 레코드 값을 테이블 형태로 가진 객체

  • ResultSet 객체의 메소드 종류

executeQuery() 메소드

  • 사용 예 :

executeQuery() 메소드 예제 1

Statement에서 executeQuery() 사용
select01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sound.midi.MidiFileFormat" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - Statement(select)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<div class="container mt-4">
  <div class="row">
    <div class="col-sm-6 mx-auto">
      <table class="table table-hover table-striped">
        <thead>
          <tr>
            <th>아이디</th>
            <th>비밀번호</th>
            <th>이름</th>
          </tr>
        </thead>
        <tbody>
        <%
          ResultSet rs = null;
          Statement stmt = null;
          try {
            String sql = "SELECT * FROM member ";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
//              dbconn 의 변수와 동일한 변수를 쓰면 안됨 (passwd 사용x)
              String userId = rs.getString("id"); //varChar
              String userPw = rs.getString("passwd"); //varChar
              String userNm = rs.getString("name"); //varChar
              %>
                <tr>
                  <td><%=userId%></td>
                  <td><%=userPw%></td>
                  <td><%=userNm%></td>
                </tr>
              <%
            }
          }
          catch (SQLException e) {
            out.println("member 테이블의 데이터 조회가 실패했습니다.");
            out.println("SQLException : " + e.getMessage());
          }
          finally {
            if (rs != null) {
              rs.close();
            }
            if (stmt != null) {
              stmt.close();
            }
            if (conn != null) {
              conn.close();
            }
          }
        %>
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>


executeQuery() 메소드 예제 2

PreparedStatement에서 executeQuery() 사용 (SELECT)
select02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - PreparedStatement (select)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<div class="container mt-4">
  <div class="row">
    <div class="col-sm-6 mx-auto">
      <table class="table table-hover table-striped">
        <thead>
          <tr>
            <th>아이디</th>
            <th>비밀번호</th>
            <th>이름</th>
          </tr>
        </thead>
        <tbody>
        <%
          PreparedStatement pstmt = null;
          ResultSet rs = null;

          try {
            String sql = "SELECT * FROM member ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
              String userId = rs.getString("id");
              String userPw = rs.getString("passwd");
              String userNm = rs.getString("name");
        %>
        <tr>
          <td><%=userId%></td>
          <td><%=userPw%></td>
          <td><%=userNm%></td>
        </tr>
        <%
            }
          }
          catch (SQLException e) {
            out.println("member 테이블 데이터 조회가 실패했습니다.");
            out.println("SQLException : " + e.getMessage());
          }
          finally {
            if (rs != null) {
              rs.close();
            }
            if (pstmt != null) {
              pstmt.close();
            }
            if (conn != null) {
              conn.close();
            }
            }


        %>
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>


executeQuery() 메소드 예제 3

Statement에서 executeQuery() 사용 (UPDATE)
id, pw 가 일치하면 name 변경 가능함
update01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - Statement (update)</title>
</head>
<body>
<form action="update01_process.jsp" method="post">
  <label for="user-id">아이디</label>
  <input type="text" id="user-id" name="userId"><br>
  <label for="user-pw">비밀번호</label>
  <input type="text" id="user-pw" name="userPw"><br>
  <label for="user-name">이름</label>
  <input type="text" id="user-name" name="userName"><br>
  <button type="submit">업데이트</button>
</form>
</body>
</html>

update01_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - Statement (update)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<%
  request.setCharacterEncoding("UTF-8");

  String userId = request.getParameter("userId");
  String userPw = request.getParameter("userPw");
  String userNm = request.getParameter("userName");

  Statement stmt = null;
  ResultSet rs = null;

  try {
    String sql = "SELECT id, passwd FROM member ";
    sql += "WHERE id = '" + userId + "' ";

    stmt = conn.createStatement();
    rs = stmt.executeQuery(sql);

    if (rs.next()) {
      String rid = rs.getString("id");
      String rpw = rs.getString("passwd");

//      새로 추가
      if (userId.equals(rid) && userPw.equals(rpw)) {
        sql = "UPDATE member SET name = '" + userNm + "' ";
        sql += "WHERE id = '" + userId + "' ";

        stmt = conn.createStatement();
        stmt.executeUpdate(sql);
        out.println("member 테이블의 데이터를 수정하였습니다.");
      }
      else {
        out.println("비밀번호가 틀렸습니다.");
      }
    }
    else {
      out.println("일치하는 사용자가 없습니다.");
    }
  }
  catch (SQLException e) {
    out.println("SQLException : " + e.getMessage());
  }
  finally {
    if (rs != null) {
      rs.close();
    }
    if (stmt != null) {
      stmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }
%>
</body>
</html>

executeQuery() 메소드 예제 4

PreparedStatement에서 executeQuery() 사용 (UPDATE)

update02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - PreparedStatement (update)</title>
</head>
<body>
<form action="update02_process.jsp" method="post">
  <label for="user-id">아이디</label>
  <input type="text" id="user-id" name="userId"><br>
  <label for="user-pw">비밀번호</label>
  <input type="text" id="user-pw" name="userPw"><br>
  <label for="user-name">이름</label>
  <input type="text" id="user-name" name="userName"><br>
  <button type="submit">업데이트</button>
</form>
</body>
</html>

update02_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>DB 사용하기 - PreparedStatement (update)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<%
  request.setCharacterEncoding("UTF-8");

  String userId = request.getParameter("userId");
  String userPw = request.getParameter("userPw");
  String userNm = request.getParameter("userName");

  PreparedStatement pstmt = null;
  ResultSet rs = null;

  try {
    String sql = "SELECT id, passwd FROM member ";
    sql += "WHERE id = ? ";

    pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, userId);
    rs = pstmt.executeQuery();

    if (rs.next()) {
      String rid = rs.getString("id");
      String rpw = rs.getString("passwd");

      if  (userId.equals(rid) && userPw.equals(rpw)) {
        sql = "UPDATE member SET name = ? ";
        sql += "WHERE id = ? ";

        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, userNm);
        pstmt.setString(2, userId);
        pstmt.executeUpdate();

        out.println("member 테이블의 정보를 수정하였습니다.");
      }
      else {
        out.println("비밀번호가 틀렸습니다.");
      }
    }
    else {
      out.println("일치하는 사용자가 없습니다.");
    }
  }
  catch (SQLException e) {
    out.println("SQLException = " + e.getMessage());
  }
  finally {
    if (rs != null) {
      rs.close();
    }
    if (pstmt != null) {
      pstmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }
%>
</body>
</html>

문제1. Statement를 사용하여 DELETE 를 실행하는 프로그램을 작성하세요

  1. delete01.jsp 파일은 사용자 id와 비밀번호를 입력받는 form으로 생성
  2. delete01_process.jsp 파일은 사용자가 입력한 내용을 바탕으로 sql 쿼리를 실행
  3. 입력한 id가 없으면, [지정한 사용자가 없습니다] 출력
  4. 비밀번호가 틀리면, [비밀번호가 틀렸습니다.] 출력

delete01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>문제1. Statement를 사용하여 DELETE 를 실행하는 프로그램 작성</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="delete01_process.jsp">
  <label for="user-id">아이디</label>
  <input type="text" id="user-id" name="userId"><br>
  <label for="user-pw">비밀번호</label>
  <input type="text" id="user-pw" name="userPw"><br>
  <button type="submit">삭제</button>
</form>
</body>
</html>

delete01_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>문제1. Statement를 사용하여 DELETE 를 실행하는 프로그램 작성</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<%
    request.setCharacterEncoding("UTF-8");

    String userId = request.getParameter("userId");
    String userPw = request.getParameter("userPw");

    Statement stmt = null;
    ResultSet rs = null;

    try {
//        sql문 지정
//        id 검색
        String sql = "SELECT id, passwd FROM member ";
        sql += "WHERE id = '" + userId + "' ";

//        conn 객체 사용하여 Statement 객체 생성해줌 => dbconn에 연결
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);

//        if문으로 확인한 이유 : id(pk키)로 검색했을때는 결과가 단 2개. 있거나 없거나. 있으면 true, 없으면 false
        if (rs.next()) {
            String rid = rs.getString("id");
            String rpw = rs.getString("passwd");

            if (userId.equals(rid) && userPw.equals(rpw)) {
//                DELETE 구문 생성
                sql = "DELETE FROM member ";
                sql += "WHERE id = '" + userId + "' ";
//                기존 객체 버리고 새 객체 생성
                stmt = conn.createStatement();
//                executeUpdate()를 이용해서 DELETE문 실행
                stmt.executeUpdate(sql);

                out.println("member 테이블의 데이터를 삭제했습니다.");
            }
            else {
                out.println("비밀번호가 틀렸습니다.");
            }
        }
        else {
            out.println("지정한 사용자가 없습니다..");
        }
    }
    catch (SQLException e) {
        out.println("member테이블의 데이터를 삭제하지 못했습니다.");
        out.println("SQLException : " + e.getMessage());
    }
    finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
%>
</body>
</html>

문제2. PreparedStatement를 사용하여 DELETE를 실행하는 프로그램을 작성하세요

  1. delete02.jsp 파일은 사용자 id와 비밀번호를 입력받는 form으로 생성
  2. delete02_process.jsp 파일은 사용자가 입력한 내용을 바탕으로 sql 쿼리를 실행
  3. 입력한 id가 없으면, [지정한 사용자가 없습니다] 출력
  4. 비밀번호가 틀리면, [비밀번호가 틀렸습니다.] 출력

게시판 만들기

글 쓰고 글 내리는 형식 (id, pw 기능 없이)

화면부분

  1. DB 필요(BBS 테이블 1개)
  2. 메인화면 중간의 게시판에 테이블 내용 들어가고 우측아래에 글쓰기 버튼
  3. 리스트 페이지 1개, 글쓰기 페이지 1개(목록돌아가기 버튼, 쓰기 버튼), 수정 페이지 1개(글쓰기 페이지와 동일), 읽기 페이지 1개(목록 버튼, 수정 버튼, 삭제 버튼) -> 화면은 총 4개

리스트 페이지

boardList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<header class="container mt-3">
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-4">
      <h1 class="text-center">게시물 리스트 페이지</h1>
    </div>
  </div>
</header>
<main class="container mt-4">
  <div class="row">
    <div class="col-sm">
      <table class="table table-hover table-striped">
        <thead>
          <tr>
            <th>글번호</th>
            <th>글제목</th>
            <th>글쓴이</th>
            <th>등록시간</th>
            <th>조회수</th>
          </tr>
        </thead>
        <tbody>
        <%
          PreparedStatement pstmt = null;
          ResultSet rs = null;

          try {
//    전체 글 조회 쿼리문
            String sql = "SELECT seq, title, user_id, create_date, cnt FROM board WHERE deleted_yn = 'N' ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
              int seq = rs.getInt("seq");
              String title = rs.getString("title");
              String userId = rs.getString("user_id");
              String createDt = rs.getString("create_date");
              int cnt = rs.getInt("cnt");
        %>
          <tr>
            <td><%=seq%>></td>
            <td><%=title%></td>
            <td><%=userId%></td>
            <td><%=createDt%></td>
            <td><%=cnt%></td>
          </tr>
        <%
            }
          }
          catch (SQLException e) {
            out.println("SQLException : " + e.getMessage());
          }
          finally {
            if (rs != null) {
              rs.close();
            }
            if (pstmt != null) {
              pstmt.close();
            }
            if (conn != null) {
              conn.close();
            }
            }
        %>
        </tbody>
      </table>
      <div class="d-flex justify-content-end">
        <a href="boardWrite.jsp" class="btn btn-primary">글쓰기</a>
      </div>
    </div>
  </div>
</main>
<footer class="container-fluid mt-5 p-5 border-top">
  <p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>
</html>

읽기 페이지

쓰기 페이지

boardWrite.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>게시판 글쓰기 페이지</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>

  <script>
<%--    자바스크립트  --%>
    window.addEventListener('DOMContentLoaded', function () {
      const btnBack = document.querySelector('#btn-back');
      btnBack.addEventListener('click', function () {
        //뒤로가기 기능
        history.back();
      })
    });
  </script>
</head>
<body>
<header class="container mt-3">
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-4">
      <h1 class="text-center">게시물 글쓰기 페이지</h1>
    </div>
  </div>
</header>


<main class="container mt-5">
  <div class="row">
    <div class="col-sm-6 mx-auto">
      <form action="boardWrite_process.jsp" method="post" class="border rounded-3 p-4">
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="title" name="title" placeholder="제목을 입력하세요">
          <label for="title" class="form-label">Title</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="user-id" name="userId" placeholder="ID를 입력하세요">
          <label for="user-id" class="form-lavel">ID</label>
        </div>
        <div class="form-floating my-3">
          <textarea class="form-control" id="contents" name="contents" placeholder="내용을 입력하세요" ></textarea>
          <label for="contents" class="form-label">Contents...</label>
        </div>
        <div class="d-grid gap-2">
          <button class="btn btn-primary" type="submit">글쓰기</button>
          <button class="btn btn-secondary" type="button" id="btn-back">돌아가기</button>
        </div>
      </form>
    </div>
  </div>
</main>


<footer class="container-fluid mt-5 p-5 border-top">
  <p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>
</html>

boardWrite_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ include file="dbconn.jsp"%>

<%
    request.setCharacterEncoding("UTF-8");

    String title = request.getParameter("title");
    String userId = request.getParameter("userId");
    String contents = request.getParameter("contents");

    PreparedStatement pstmt = null;
//    INSERT 해줄거라서 rs 필요없음

    try {
        String sql = "INSERT INTO board (title, contents, user_id, create_date) ";
        sql += "VALUES (?, ?, ?, now()) ";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, title);
        pstmt.setString(2, contents);
        pstmt.setString(3, userId);
        pstmt.executeUpdate();

    }
    catch (SQLException e) {
        out.println("SQLException : " + e.getMessage());
    }
    finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
//  실행 다 되고나면 첫 페이지로 돌아가게 만들기
    response.sendRedirect("boardList.jsp");

%>

0개의 댓글