자바 웹 쿠키에 대한 질문
-
게시물 수정 , 삭제는 로그인 필요
수정 버튼을 누를 때 마다 쿠키의 title 값을 받고 그걸로 생성하는데 문제는
처음 받는 쿠키값을 잘 읽는데 다음 수정 버튼을 받아 만든 쿠키 내용은 (업데이트됌)
그 값은 자꾸 null로 읽습니다 .. 어떻게 하면 쿠키값을 null로 안되게 할까요??
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.sql.*"
import="java.util.*"
import="java.util.Date"
import="sec1.*"
pageEncoding="UTF-8"
%>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
<%
String title = "";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 수정하기</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
button {
padding: 6px 12px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>글 수정</h2>
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성일</th>
<th></th>
</tr>
</thead>
<tbody>
<%
// 데이터베이스 연결
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 데이터베이스 연결 정보 설정
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##scott";
String dbPassword = "tiger";
// 데이터베이스에 연결
conn = DriverManager.getConnection(url, user, dbPassword);
// 현재 아이디(userId) 가져오기
String userId = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("userId")) {
userId = cookie.getValue();
break;
}
}
}
// userId에 해당하는 작성자 게시글 조회
String sql = "SELECT * FROM 게시판 WHERE 작성자 = ? ORDER BY 날짜 ASC";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
// 결과 출력
while (rs.next()) {
int strNum = rs.getInt("글번호");
title = rs.getString("제목");
Date writeDate = rs.getDate("날짜");
// 출력 처리
%>
<tr>
<td><%= strNum %></td>
<td><%= title %></td>
<td><%= writeDate %></td>
<td>
<!-- 수정 버튼에 onclick 이벤트 핸들러 추가 -->
<button onclick="editPost('<%= title %>')">수정</button>
</td>
</tr>
<%
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 리소스 해제
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</tbody>
</table>
<div id="editForm" style="display: none;">
<h2>게시글 수정</h2>
<!-- 게시글 내용을 입력할 textarea -->
<textarea id="postContent" rows="5" cols="50"></textarea><br>
<!-- 수정 버튼의 onclick 이벤트 핸들러 변경 -->
<button onclick="updatePost()">글 수정완료</button>
</div>
</div>
<script>
function editPost(title) {
// 기존의 title 쿠키가 존재하는지 확인하고 제거합니다.
if (document.cookie.includes("title")) {
document.cookie = "title=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// AJAX를 사용하여 서버에 게시물 내용 요청을 보냅니다.
$.ajax({
url: "getPostContent.jsp", // 게시물 내용을 가져올 서버 측 JSP 파일 경로
type: "POST",
data: { title: title }, // 게시물의 제목을 전달
success: function(response) {
// 서버에서 게시물 내용을 성공적으로 가져오면,
// 입력창에 게시물 내용을 설정합니다.
$("#postContent").val(response);
// 수정 폼을 표시합니다.
$("#editForm").show();
// 수정할 게시물의 제목을 쿠키에 저장합니다.
document.cookie = "title=" + title + "; path=/"; // 쿠키 생성
},
error: function(xhr, status, error) {
// 서버에서 게시물 내용을 가져오지 못한 경우,
// 이곳에 오류 처리 코드를 작성할 수 있습니다.
console.error(error);
}
});
}
function updatePost() {
// 수정된 게시글 내용을 가져옴
var content = $("#postContent").val();
// AJAX를 사용하여 서버에 게시글 내용을 업데이트하는 요청을 보냅니다.
$.ajax({
url: "updatePost.jsp", // 게시글 내용을 업데이트할 서버 측 JSP 파일 경로
type: "POST",
data: { content: content }, // 내용을 전달
success: function(response) {
// 성공적으로 업데이트된 경우, 적절한 처리를 수행합니다.
alert("수정 완료");
console.log(response);
},
error: function(xhr, status, error) {
// 서버에서 게시글 내용을 업데이트하지 못한 경우,
// 이곳에 오류 처리 코드를 작성할 수 있습니다.
console.error(error);
}
});
}
</script>
</body>
</html>
updatePost.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.sql.*"
import="java.util.*"
import="java.util.Date"
import="sec1.*"
pageEncoding="UTF-8"
%>
<%
//쿠키에서 제목 가져오기
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
String path = cookie.getPath();
String domain = cookie.getDomain();
int maxAge = cookie.getMaxAge();
System.out.println("Name: " + name);
System.out.println("Value: " + value);
System.out.println("Path: " + path);
System.out.println("Domain: " + domain);
System.out.println("Max Age: " + maxAge);
System.out.println("------------------------");
}
}
String title = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("title")) {
title = cookie.getValue();
break;
}else{System.out.println("title 쿠키 없음");}
}
}
System.out.println("cookie = " + title);
String content = request.getParameter("content");
// 데이터베이스 연결
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 데이터베이스 연결 정보 설정
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##scott";
String dbPassword = "tiger";
// 데이터베이스에 연결
conn = DriverManager.getConnection(url, user, dbPassword);
// 게시글 수정
String sql = "UPDATE 게시판 SET 내용 = ? WHERE 제목 = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, content);
pstmt.setString(2, title);
int rowCount = pstmt.executeUpdate();
if (rowCount > 0) {
System.out.println("게시글이 수정되었습니다.");
} else {
System.out.println("게시글 수정에 실패했습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("오류 발생: " + e.getMessage());
} finally {
// 리소스 해제
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
수정 버튼을 누를 때 마다 쿠키의 title 값을 받고 그걸로 생성하는데 문제는
처음 받는 쿠키값을 잘 읽는데 다음 수정 버튼을 받아 만든 쿠키 내용은 (업데이트됌)
그 값은 자꾸 null로 읽습니다 .. 어떻게 하면 쿠키값을 null로 안되게 할까요??
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.sql.*"
import="java.util.*"
import="java.util.Date"
import="sec1.*"
pageEncoding="UTF-8"
%>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
<%
String title = "";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 수정하기</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
button {
padding: 6px 12px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>글 수정</h2>
<table>
<thead>
<tr>
<th>글번호</th>
<th>제목</th>
<th>작성일</th>
<th></th>
</tr>
</thead>
<tbody>
<%
// 데이터베이스 연결
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 데이터베이스 연결 정보 설정
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##scott";
String dbPassword = "tiger";
// 데이터베이스에 연결
conn = DriverManager.getConnection(url, user, dbPassword);
// 현재 아이디(userId) 가져오기
String userId = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("userId")) {
userId = cookie.getValue();
break;
}
}
}
// userId에 해당하는 작성자 게시글 조회
String sql = "SELECT * FROM 게시판 WHERE 작성자 = ? ORDER BY 날짜 ASC";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
// 결과 출력
while (rs.next()) {
int strNum = rs.getInt("글번호");
title = rs.getString("제목");
Date writeDate = rs.getDate("날짜");
// 출력 처리
%>
<tr>
<td><%= strNum %></td>
<td><%= title %></td>
<td><%= writeDate %></td>
<td>
<!-- 수정 버튼에 onclick 이벤트 핸들러 추가 -->
<button onclick="editPost('<%= title %>')">수정</button>
</td>
</tr>
<%
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 리소스 해제
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</tbody>
</table>
<div id="editForm" style="display: none;">
<h2>게시글 수정</h2>
<!-- 게시글 내용을 입력할 textarea -->
<textarea id="postContent" rows="5" cols="50"></textarea><br>
<!-- 수정 버튼의 onclick 이벤트 핸들러 변경 -->
<button onclick="updatePost()">글 수정완료</button>
</div>
</div>
<script>
function editPost(title) {
// 기존의 title 쿠키가 존재하는지 확인하고 제거합니다.
if (document.cookie.includes("title")) {
document.cookie = "title=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// AJAX를 사용하여 서버에 게시물 내용 요청을 보냅니다.
$.ajax({
url: "getPostContent.jsp", // 게시물 내용을 가져올 서버 측 JSP 파일 경로
type: "POST",
data: { title: title }, // 게시물의 제목을 전달
success: function(response) {
// 서버에서 게시물 내용을 성공적으로 가져오면,
// 입력창에 게시물 내용을 설정합니다.
$("#postContent").val(response);
// 수정 폼을 표시합니다.
$("#editForm").show();
// 수정할 게시물의 제목을 쿠키에 저장합니다.
document.cookie = "title=" + title + "; path=/"; // 쿠키 생성
},
error: function(xhr, status, error) {
// 서버에서 게시물 내용을 가져오지 못한 경우,
// 이곳에 오류 처리 코드를 작성할 수 있습니다.
console.error(error);
}
});
}
function updatePost() {
// 수정된 게시글 내용을 가져옴
var content = $("#postContent").val();
// AJAX를 사용하여 서버에 게시글 내용을 업데이트하는 요청을 보냅니다.
$.ajax({
url: "updatePost.jsp", // 게시글 내용을 업데이트할 서버 측 JSP 파일 경로
type: "POST",
data: { content: content }, // 내용을 전달
success: function(response) {
// 성공적으로 업데이트된 경우, 적절한 처리를 수행합니다.
alert("수정 완료");
console.log(response);
},
error: function(xhr, status, error) {
// 서버에서 게시글 내용을 업데이트하지 못한 경우,
// 이곳에 오류 처리 코드를 작성할 수 있습니다.
console.error(error);
}
});
}
</script>
</body>
</html>
updatePost.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.sql.*"
import="java.util.*"
import="java.util.Date"
import="sec1.*"
pageEncoding="UTF-8"
%>
<%
//쿠키에서 제목 가져오기
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
String path = cookie.getPath();
String domain = cookie.getDomain();
int maxAge = cookie.getMaxAge();
System.out.println("Name: " + name);
System.out.println("Value: " + value);
System.out.println("Path: " + path);
System.out.println("Domain: " + domain);
System.out.println("Max Age: " + maxAge);
System.out.println("------------------------");
}
}
String title = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("title")) {
title = cookie.getValue();
break;
}else{System.out.println("title 쿠키 없음");}
}
}
System.out.println("cookie = " + title);
String content = request.getParameter("content");
// 데이터베이스 연결
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 데이터베이스 연결 정보 설정
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "c##scott";
String dbPassword = "tiger";
// 데이터베이스에 연결
conn = DriverManager.getConnection(url, user, dbPassword);
// 게시글 수정
String sql = "UPDATE 게시판 SET 내용 = ? WHERE 제목 = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, content);
pstmt.setString(2, title);
int rowCount = pstmt.executeUpdate();
if (rowCount > 0) {
System.out.println("게시글이 수정되었습니다.");
} else {
System.out.println("게시글 수정에 실패했습니다.");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("오류 발생: " + e.getMessage());
} finally {
// 리소스 해제
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
#자바 웹 컴파일러 #자바 웹개발 #자바 웹 개발 워크북 #자바 웹 프로그래밍 #자바 웹소켓 #자바 웹을 다루는 기술 #자바 웹 프로그래밍 next step #자바 웹페이지 만들기 #자바 웹 ide #자바 웹 크롤링