Notice
Recent Posts
Recent Comments
Links
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Today
In Total
관리 메뉴

A Joyful AI Research Journey🌳😊

[60] 230324 JSP: 카페 글쓰기 기능, 게시판 목록 구현하기 [K-디지털 트레이닝 60일] 본문

🌳Bootcamp Revision✨/HTML5, CSS3, JSP

[60] 230324 JSP: 카페 글쓰기 기능, 게시판 목록 구현하기 [K-디지털 트레이닝 60일]

yjyuwisely 2023. 3. 24. 11:52

230324 60th class

진도: 교재가 아닌 자체 수업 (교재: 최범균의 JSP 2.3 웹 프로그래밍: 기초부터 중급까지, 저자: 최범균)
책 예제 코드: https://github.com/madvirus/jsp23
저자 블로그: https://javacan.tistory.com/

 

최범균의 JSP 2.3 웹 프로그래밍: 기초부터 중급까지 | 최범균 - 교보문고

최범균의 JSP 2.3 웹 프로그래밍: 기초부터 중급까지 | [최범균의 JSP 2.3 웹 프로그래밍 기초부터 중급까지]는 JSP 2.3의 새로운 특징 반영과 JSP를 지원하는 요소인 서블릿과 표현 언어 등의 새로운

product.kyobobook.co.kr


오늘 배운 것 중 기억할 것을 정리했다.


viewBorderList.jsp ViewBoardDetail.jsp
의 코드는 아래 글에서 볼 수 있다.

2023.03.23 - [🌳K-Digital Revision 2023✨/JSP] - [59] 230323 JSP Ch. 14 데이터베이스 프로그래밍 기초 [K-디지털 트레이닝 59일]


요약

[1] viewBoardList.jsp
게시판 목록 리스트
select(여러 건) -> ResultSet(에 저장) -> while(rs.next())

//select의 결과를 DBMS에서 java로 저장하기 위한 객체
ResultSet rs = null;

[2] viewBoardDetail.jsp
게시판 목록 리스트 -> 제목 클릭 -> 게시판 상세 내용

select(한건) -> ResultSet -> if(rs.nex())

=====================================================

[3] modifyBoard.jsp
게시판 상세 내용 -> 수정 
(게시판 상세 내용 -> 수정 버튼 -> 수정 화면 -> 수정 (ex. 네이버 카페의 경우))

update -> update 됨 -> 게시판 상세 내용 화면으로(viewDetailList.jsp)

[4] deleteBoard.jsp
게시판 상세 내용 -> 삭제
delete
-> delete -> 게시판 목록 리스트 화면으로(viewBoardList.jsp)

[5] insertBoard.jsp
게시판 글쓰기 화면 -> 글쓰기 -> 제목, 내용을 서버로 전송 

[6] insertBoardServer.jsp
DB작업
insert -> insert 됨 -> 게시판 목록 리스트 화면으로(viewBoardList.jsp)

카페 글쓰기 jsp 예제

네이버 카페 게시판 (예시)

get 방식일 경우 아래와 같다. 하지만 코드에서 post로 지정했다.

http://localhost:8081/insertBoardServer.jsp?title=제목입니다.&content=내용등등
<!-- 제목입니다 -> title -->
<!-- 내용등등 -> content -->
<!-- title, content -> insertBoardServer.jsp -->

MySQL에 데이터를 넣기 위해 쓰는 코드는 아래와 같다. 
참고: 2023.03.17 - [🌳K-Digital Revision 2023✨/SQL] - [54~55] 230316, 230317 SQL 문제 풀이 (member, board 테이블) [K-디지털 트레이닝 54~55일]

SELECT * FROM sample.board;
ALTER TABLE `sample`.`board`
CHANGE COLUMN `count` `count` INT NULL DEFAULT 0 COMMENT '조회수' ; -- 조회수의 디폴트값을 0으로 만든다.
ALTER TABLE `sample`.`board`
DROP FOREIGN KEY `board_ibfk_1`;
ALTER TABLE `sample`.`board`
CHANGE COLUMN `title` `title` VARCHAR(50) NOT NULL COMMENT '제목' , -- 입력할 수 있는 길이를 바꾼다.
CHANGE COLUMN `content` `content` VARCHAR(100) NULL DEFAULT NULL COMMENT '내용' , -- 입력할 수 있는 길이를 바꾼다.
CHANGE COLUMN `id` `id` VARCHAR(20) NULL DEFAULT NULL COMMENT '작성자' ; -- 입력할 수 있는 길이를 바꾼다.
ALTER TABLE `sample`.`board`
ADD CONSTRAINT `board_ibfk_1`
FOREIGN KEY (`id`)
REFERENCES `sample`.`member` (`id`);
insert into board (title, content, id) values ('안녕하세요', '오늘 정모 있습니다.','abcd');
insert into board (title, content) values ('안녕하세요', '오늘 정모 있습니다.');
insert into board(title, content) values('제목', '내용');
SELECT * FROM sample.board;

코드) 게시판 글쓰기 테이블 insertBoard.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>
<form action = "insertBoardServer.jsp" method="post"> <!-- 글쓰기를 하기 위한 서버.jsp -->
<table border="1">
<tr>
<td>제목</td>
<td><input type="text"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea rows="10" cols="30"></textarea></td>
</tr>
<tr>
<td colspan="2"><!-- 좌우의 셀들을 병합한다 (가로로 합침, 가로가 긴 직사각형) -->
<input type="submit" value="글쓰기">
</td>
</tr>
</table>
</form>
</body>
</html>

결과)


코드) 글쓰기 테이블 insertBoard.jsp
처음에 오류가 났는 데 name과 그 값을 넣어야 한다.
name = "title", name = "content"

<input type="text" name="title">
<textarea rows="10" cols="30" name="content"></textarea>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>카페 글쓰기</title>
</head>
<body>
<form action = "insertBoardServer.jsp" method="post"> <!-- 글쓰기를 하기 위한 서버.jsp -->
<table border="1">
<tr>
<td>제목</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea rows="10" cols="30" name="content"></textarea></td>
</tr>
<tr>
<td colspan="2"><!-- 좌우의 셀들을 병합한다 (가로로 합침, 가로가 긴 직사각형) -->
<input type="submit" value="글쓰기">
</td>
</tr>
</table>
</form>
</body>
</html>

서버 코드) 게시판 글쓰기의 서버 insertBoardServer.jsp
처음에 오류가 났는데 아래 코드를 빼먹어서다.

pstmt = conn.prepareStatement(query);

또 MySQL에서 테이블 체크했을 때 POST 방식은 charset=UTF-8 적용이 안 되므로 MySQL에서의 한글 깨짐 해결을 위해 아래 코드를 넣는다. 

<% request.setCharacterEncoding("utf-8"); %> <!-- 한글깨짐 해결 -->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<% request.setCharacterEncoding("utf-8"); %> <!-- 한글깨짐 해결 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 글쓰기 서버</title>
</head>
<body>
<%
String title = request.getParameter("title");
String content = request.getParameter("content");
// 1. JDBC 드라이버 로딩(mysql)
Class.forName("com.mysql.jdbc.Driver");
//java api에 db을 연결하기 위한 객체
Connection conn = null;
//workbench sql을 작성한 후 ctrl+enter(결과도출)
//sql문장을 작성을 하고, 그 sql문장을 실행하기 위한 객체
//Statement stmt = null;
PreparedStatement pstmt = null;
try{
String jdbcDriver = "jdbc:mysql://localhost:3306/sample?serverTimezone=Asia/Seoul";
String dbUser = "root";
String dbPass = "1234";
//2. 데이터베이스 커넥션 생성
conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
// 여기까지가 DB 연결 코드
//3. Statement 생성
//SQL 코드 복사
String query = "insert into board(title, content) values(?, ?)"; //물음표(?) 처리로 사용자가 입력한 값을 넣게 된다.
pstmt = conn.prepareStatement(query);
pstmt.setString(1, title); //첫번째 물음표에는 title값을 넣어라.
pstmt.setString(2, content); //두번째 물음표에는 content값을 넣어라.
//4. 쿼리 실행
//workbench에서 ctrl+enter(쿼리문장을 실행)를 통해 도출된 select결과를 Resultset에 저장
//rs = pstmt.executeQuery();
pstmt.executeUpdate(); //insert작업 때 select일 때 executeUpdate()를 사용한다. 나머지는 rs=pstmt.executeQuery();를 쓴다.
}catch(Exception ex){
System.out.println(ex.getMessage()); //콘솔에 오류 메시지를 띄운다.
out.println("DB 연결 실패");
}finally{
if(conn!=null){conn.close();}
}
%>
</body>
</html>

제목과 내용을 넣어본다.

결과) MySQL에 한글 깨짐 없이 데이터가 4번 글로 들어갔다.

MySQL의 결과


전체 코드) 게시판 글쓰기 테이블의 서버 insertBoardServer.jsp
내용 입력 후 게시판 목록 리스트로 이동한다.

추가 한 코드는 아래와 같다.

//insert 한 후 게시판 목록 리스트 화면(viewBoardList.jsp)으로 이동하라고 응답한다.
response.sendRedirect("viewBoardList.jsp");
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<% request.setCharacterEncoding("utf-8"); %> <!-- 한글깨짐 해결 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 글쓰기 서버</title>
</head>
<body>
<%
String title = request.getParameter("title");
String content = request.getParameter("content");
// 1. JDBC 드라이버 로딩(mysql)
Class.forName("com.mysql.jdbc.Driver");
//java api에 db을 연결하기 위한 객체
Connection conn = null;
//workbench sql을 작성한 후 ctrl+enter(결과도출)
//sql문장을 작성을 하고, 그 sql문장을 실행하기 위한 객체
//Statement stmt = null;
PreparedStatement pstmt = null;
try{
String jdbcDriver = "jdbc:mysql://localhost:3306/sample?serverTimezone=Asia/Seoul";
String dbUser = "root";
String dbPass = "1234";
//2. 데이터베이스 커넥션 생성
conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
// 여기까지가 DB 연결 코드
//3. Statement 생성
//SQL 코드 복사
String query = "insert into board(title, content) values(?, ?)"; //물음표(?) 처리로 사용자가 입력한 값을 넣게 된다.
pstmt = conn.prepareStatement(query);
pstmt.setString(1, title); //첫번째 물음표에는 title값을 넣어라.
pstmt.setString(2, content); //두번째 물음표에는 content값을 넣어라.
//4. 쿼리 실행
//workbench에서 ctrl+enter(쿼리문장을 실행)를 통해 도출된 select결과를 Resultset에 저장
//rs = pstmt.executeQuery();
pstmt.executeUpdate(); //insert가 정상적으로 처리. insert작업 때 select일 때 executeUpdate()를 사용한다. 나머지는 rs=pstmt.executeQuery();를 쓴다.
//insert 한 후 게시판 목록 리스트 화면(viewBoardList.jsp)으로 이동하라고 응답한다.
response.sendRedirect("viewBoardList.jsp");
}catch(Exception ex){
System.out.println(ex.getMessage()); //콘솔에 오류 메시지를 띄운다.
out.println("DB 연결 실패");
}finally{
if(conn!=null){conn.close();}
}
%>
</body>
</html>

제목과 내용을 입력한다.

결과)

글쓰기 버튼을 누르면 바로 게시판 목록으로 간다.
제목입니다2를 클릭했다. (이 그림은 밑 줄부터 아래 코드들의 수정 전이다.)


<수정, 삭제 버튼 작동하기 하기>

참고

정의 및 특징
<input> 태그의 formaction 속성은 폼 데이터(form data)가 서버로 제출될 때 입력 데이터를 처리할 파일의 URL을 명시함.
 
이 속성은 <input> 요소의 type 속성값이 “submit” 또는 “image”인 경우에만 사용할 수 있습니다.
formaction 속성은 <form> 요소의 action 속성값을 재정의(overriding)합니다.

문법
<input type="submit|image" formaction="URL">

참고: http://www.tcpschool.com/html-tag-attrs/input-formaction


 

수정, 삭제 버튼을 만드는 아래 코드를 추가한다.
<form method="post">를 쓴다.

<form method="post">
<table>
<!-- (중략) -->
</table>
<input type="submit" value="수정" formaction="modifyBoard.jsp">
<input type="submit" value="삭제" formaction="removeBoard.jsp">
</form>

오류가 났었는데 아래 코드에서 <%=rs.getString("content") %>의 위치를 잘못 넣어서이다.
<textarea> </textarea> 사이에 <%=rs.getString("content") %>을 넣는다.

<textarea name="content" rows="10" cols="30"><%=rs.getString("content") %></textarea>

또 <form>을 아래 코드로 수정해야 수정 버튼을 눌렀을 때 아래 no를 포함한 URL이 유지된다.

<form method="post">

http://localhost:8081/JSPExample/ch14/viewBoardDetail.jsp?no=8

<form>으로 두면 URL의 경로가 자체 jsp 파일인 http://localhost:8081/JSPExample/ch14/viewBoardDetail가 된다.


내가 헷갈렸던 것 (타이핑 형태가 아닌 읽는 형태로 만들려면 readonly나 type="hidden" 사용하기)

<!-- 첫번째 방법 readonly 쓴다. -->
번호: <input type="text" name="no" value="<%=rs.getString("no") %>" readonly>
<!-- 두번째 방법: hidden 쓴다. -->
번호: <%=rs.getInt("no") %> <input type="hidden" name="no" value="<%=rs.getString("no") %>">

type="text"로 뒀을 때 입력칸이 생겨서 아무거나 타이핑 가능하다.
type = "hidden"으로 뒀을 때 입력 칸이 숨겨진다.

전체 코드) 수정, 삭제 버튼을 추가한 viewBoardDetail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head><title>게시판 내용</title></head>
<body>
<%
//method방식이 post일 때 한글깨짐 방지
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("no"));
// 1. JDBC 드라이버 로딩(mysql)
Class.forName("com.mysql.jdbc.Driver");
//java api에 db을 연결하기 위한 객체
Connection conn = null;
//workbench sql을 작성한 후 ctrl+enter(결과도출)
//sql문장을 작성을 하고, 그 sql문장을 실행하기 위한 객체
//Statement stmt = null;
PreparedStatement pstmt = null;
//select의 결과를 DBMS에서 java로 저장하기 위한 객체
ResultSet rs = null;
//연결하기
//드라이브 매니저에게 Connection객체를 달라고 요청한다.
//Connection을 얻기 위해 필요한 데이터(url,id,비밀번호)
try{
String jdbcDriver = "jdbc:mysql://localhost:3306/sample?serverTimezone=Asia/Seoul";
String dbUser = "root";
String dbPass = "1234";
//2. 데이터베이스 커넥션 생성
conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
String query = "select * from board where no =?"; //executeQuery
//3. Statement 생성
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, no); //#####첫번째 물음표에는 no값을 넣어라.#####
//4. 쿼리 실행
//workbench에서 ctrl+enter(쿼리문장을 실행)를 통해 도출된 select결과를 Resultset에 저장
rs = pstmt.executeQuery();
//pstmt.executeUpdate();
//5. 쿼리 실행 결과 출력
//rs.next: 테이블에서 밑 행으로 내려온다. 데이터가 있으면 결과가 true (while문이 true)이므로 반복한다.
//while문이 false이면 종료
if(rs.next()){
%>
<!-- 여기에 게시판 글 나오게 만든다. -->
<form method="post">
<table border="1">
<tr>
<td colspan=2>
<!-- 번호: <input type="text" name="no" value="<%=rs.getString("no") %>" readonly> --> <!-- 첫번째 방법 -->
번호: <%=rs.getInt("no") %> <input type="hidden" name="no" value="<%=rs.getString("no") %>"> <!-- 두번째 방법: hidden 쓴다. -->
조회수: <%=rs.getInt("count") %>
좋아요: <%=rs.getInt("good") %>
</td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="title" value="<%=rs.getString("title") %>"></td> <!-- input 태그를 넣어서 title 편집 가능하다. -->
</tr>
<tr>
<td>내용</td>
<td><textarea name="content" rows="10" cols="30"><%=rs.getString("content") %></textarea></td> <!-- input 태그를 넣어서 content 편집 가능하다. -->
</tr>
<tr>
<td colspan="2">
<input type="submit" value="수정" formaction="modifyBoard.jsp">
<input type="submit" value="삭제" formaction="removeBoard.jsp">
</td>
</tr>
</table>
</form>
<%
} // if end
//out.println("DB 연결 성공");
}catch(SQLException ex){
out.println("DB 연결 실패");
}finally{
if(conn!=null){conn.close();}
}
%>
</body>
</html>


전체 코드) 게시글 수정 버튼이 작동한다.
modifyBoard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 수정 버튼 작동</title>
</head>
<body>
<%
//method방식이 post일 때 한글깨짐 방지
request.setCharacterEncoding("utf-8");
//게시판 번호
int no = Integer.parseInt(request.getParameter("no"));
//제목
String title = request.getParameter("title");
//내용
String content = request.getParameter("content");
System.out.println("no=>"+no);
System.out.println("title=>"+title);
System.out.println("content=>"+content);
// 1. JDBC 드라이버 로딩(mysql)
Class.forName("com.mysql.jdbc.Driver");
//java api에 db을 연결하기 위한 객체
Connection conn = null;
//workbench sql을 작성한 후 ctrl+enter(결과도출)
//sql문장을 작성을 하고, 그 sql문장을 실행하기 위한 객체
//Statement stmt = null;
PreparedStatement pstmt = null;
try{
String jdbcDriver = "jdbc:mysql://localhost:3306/sample?serverTimezone=Asia/Seoul";
String dbUser = "root";
String dbPass = "1234";
//2. 데이터베이스 커넥션 생성
conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
String query = "update board set title=?, content=? where no=?"; //executeQuery
//3. Statement 생성
pstmt = conn.prepareStatement(query);
pstmt.setString(1, title); //1번째 물음표에는 title값을 넣어라.
pstmt.setString(2, content); //2번째 물음표에는 content값을 넣어라.
pstmt.setInt(3, no); //3번째 물음표에는 no값을 넣어라.
//4. 쿼리 실행
//workbench에서 ctrl+enter(쿼리문장을 실행)를 통해 도출된 select결과를 Resultset에 저장
//rs = pstmt.executeQuery();
pstmt.executeUpdate();
response.sendRedirect("viewBoardDetail.jsp?no="+no); //게시판 글 자체의 viewBoardDetail.jsp가 유지된다.
}catch(Exception ex){
out.println("DB 연결 실패");
}finally{
if(conn!=null){conn.close();}
}
%>
</body>
</html>

수정 전) 제목 및 내용 수정 전이다. 

수정 후 결과) 제목 및 내용 수정 후다. 

결과)

8번 게시글을 보면 수정된 제목, 내용이 들어갔다.


게시판 글 삭제하기
코드) removeBoard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 삭제 버튼 작동</title>
</head>
<body>
<%
//method방식이 post일 때 한글깨짐 방지
request.setCharacterEncoding("utf-8");
//게시판 번호
int no = Integer.parseInt(request.getParameter("no"));
//제목
String title = request.getParameter("title");
//내용
String content = request.getParameter("content");
System.out.println("no=>"+no);
System.out.println("title=>"+title);
System.out.println("content=>"+content);
// 1. JDBC 드라이버 로딩(mysql)
Class.forName("com.mysql.jdbc.Driver");
//java api에 db을 연결하기 위한 객체
Connection conn = null;
//workbench sql을 작성한 후 ctrl+enter(결과도출)
//sql문장을 작성을 하고, 그 sql문장을 실행하기 위한 객체
//Statement stmt = null;
PreparedStatement pstmt = null;
try{
String jdbcDriver = "jdbc:mysql://localhost:3306/sample?serverTimezone=Asia/Seoul";
String dbUser = "root";
String dbPass = "1234";
//2. 데이터베이스 커넥션 생성
conn = DriverManager.getConnection(jdbcDriver,dbUser,dbPass);
String query = "DELETE FROM board WHERE no=?;"; //executeQuery
//String query = "update board set title=?, content=? where no=?"; //executeQuery
//3. Statement 생성
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, no); //첫번째 물음표에는 no값을 넣어라.
//4. 쿼리 실행
//workbench에서 ctrl+enter(쿼리문장을 실행)를 통해 도출된 select결과를 Resultset에 저장
//rs = pstmt.executeQuery();
pstmt.executeUpdate();
response.sendRedirect("viewBoardList.jsp"); //게시판 목록인 viewBoardList.jsp로 간다.
}catch(Exception ex){
out.println("DB 연결 실패");
}finally{
if(conn!=null){conn.close();}
}
%>
</body>
</html>

삭제 전)

게시글 7번을 삭제하기 전

삭제 후)

게시글 7번을 삭제한 후 바로 게시판 목록으로 넘어갔다.

번외) viewBoardList.jsp에 아래 코드를 추가해서 글쓰기 버튼을 추가한다.

<form><input type="submit" value="글쓰기1" formaction="insertBoard.jsp"></form>
<a href="insertBoard.jsp">글쓰기2</a>

결과)

글쓰기1 버튼과 글쓰기2 링크가 생긴다.
게시판 목록에서 글쓰기가 된다.


728x90
반응형
Comments