프로그래밍/Java 공부

자바 Servlet - 세션 이용 글 수정 기능

개발계발게발 2021. 7. 7. 16:57
반응형

자바 Servlet - 세션 이용 글 수정 기능

 

Update.java(servlet)

package com.knowhoon.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.knowhoon.dao.BoardDAO;
import com.knowhoon.dto.BoardDTO;
import com.knowhoon.util.Util;

@WebServlet("/update")
public class Update extends HttpServlet {
	private static final long serialVersionUID = 1L;
	BoardDAO dao;

	public Update() {
		super();
		dao = new BoardDAO();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = request.getSession();
		String id = (String) session.getAttribute("id");
		if (request.getParameter("bno") != null && Util.str2Int2(request.getParameter("bno")) != 0 && id != null
				&& session.getAttribute("name") != null) {
			// 로그인한 상태이고 bno가 숫자인 상태
			int bno = Util.str2Int2(request.getParameter("bno"));

			BoardDTO dto = dao.update(bno, id);
//			System.out.println(dto.getBno());
//			System.out.println(dto.getBtitle());
//			System.out.println(dto.getBcontent());
			if (dto != null) {
				// DB에서 리턴된 객체가 있다면 화면그리기
				// 디스패쳐
				RequestDispatcher dispatcher = request.getRequestDispatcher("./update.jsp");
				request.setAttribute("dto", dto); // 값 전달
				dispatcher.forward(request, response);

			} else {

				response.sendRedirect("./error.jsp");
			}
		} else {
			response.sendRedirect("./error.jsp");
		}
		// dao.update(bno, id);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		// controller
		// 글수정 - > servlet(get) -> update.jsp
		// update.jsp -> servlet(post) -> board.jsp
		String id = (String) session.getAttribute("id");
	
			if (Util.str2Int2(request.getParameter("bno")) != 0 && request.getParameter("bno") != null
					&& request.getParameter("title") != null && request.getParameter("content") != null
					&& session.getAttribute("id") != null && session.getAttribute("name") != null) {
				int bno = Util.str2Int2(request.getParameter("bno"));
				String title = request.getParameter("title");
				String content = request.getParameter("content");
				BoardDTO dto = new BoardDTO();
				dto.setBno(bno);
				dto.setBtitle(title);
				dto.setBcontent(content);
				dto.setId(id);
				dao.update2(dto);
				response.sendRedirect("./detail.jsp?bno="+ bno);
			} else {
				response.sendRedirect("./error.jsp");
			}
		
			// 데이터베이스에 보내서 질의하고 결과 받고 결과 판정 DBconnection / DTO / DAO
			// PSTMT sql, ResultSet, if(){}
			// 이동할 페이지로 이동시키기
			
			//사용자의 요청이 들어오면 서블릿이 받아서 처리
			//서블릿은 DAO/DTO를 통해 데이터를 처리하고 jsp를 호출해 화면을 처리
			
			// 요청 흐름
			
			//detail.jsp에서 수정 요청 -> servlet이 -> 데이터베이스에 데이터 요청 -> 디스패처를 이용해서 data + view를 통합, 제어
			
			//update.jsp는 서블릿에서 보내온 dto를 자신의 화면에 맞게 출력
			
			//-> 수정 버튼을 누르면 update 서블릿(post)으로 이동 -> 서블릿은 dto를 만들어 dao에게 일을 시킴 -> 페이지 이동 detail.jsp?bno=번호
			}
}

 

 

BoardDAO 메소드 추가

	// 게시판 글을 수정할 메소드 update
	public BoardDTO update(int bno, String id) {
		BoardDTO dto = null;
		Connection conn = DBConnection.dbConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM board WHERE bno=? AND no=(SELECT no FROM login WHERE id=?)";
		
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, bno);
			pstmt.setString(2, id);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				dto = new BoardDTO();
				dto.setBno(rs.getInt("bno"));
				dto.setBtitle(rs.getString("btitle"));
				dto.setBcontent(rs.getString("bcontent"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {rs.close();}
				if (pstmt != null) {pstmt.close();}
				if (conn != null) {conn.close();}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		return dto;
	}
    
    public void update2(BoardDTO dto) {
		Connection conn = DBConnection.dbConnection();

		PreparedStatement pstmt = null;

		String sql = "UPDATE board SET btitle=?, bcontent=? WHERE bno=? AND no=(SELECT no FROM login WHERE id=?)";

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, dto.getBtitle());
			pstmt.setString(2, dto.getBcontent());
			pstmt.setInt(3, dto.getBno());
			pstmt.setString(4, dto.getId());
//			pstmt.execute();	//select제외한 나머지
//			pstmt.executeQuery(); //select
			int cnt = pstmt.executeUpdate(); //영향 받은 행이 몇개 ? 리턴 타입 int
			System.out.println(cnt + " 행이 영향을 받았습니다.");

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

 

detail.jsp

<%@page import="com.knowhoon.util.Util"%>
<%@page import="com.knowhoon.dto.BoardDTO"%>
<%@page import="com.knowhoon.dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>detail</title>
<style type="text/css">

#detail{
	margin: 0 auto;
	width: 800px;
	height: 600px;
	background-color: white;
}
#title{
	width: 100%;
	height: 40px;
	padding: 10px;
	background-color: ;
	border-bottom: 2px solid black;
	box-sizing: border-box;
	text-align: center;
}
#date{
	width: 100%;
	height: 50px;
	background-color:;
	border-bottom: 1px solid gray; 
}
#date2{
	width: 150px;
	height: 20px;
	background-color:;
	float: right;
	margin: 10px;
	padding: 5px;
	text-align: center;
}
#count{
	width: 50px;
	height: 20px;
	background-color:;
	float: right;
	margin: 10px;
	padding: 5px;
	text-align: center;
}
#content{
	height: calc(100% - 91px);
	width: 100%;
	background-color:;
	padding: 20px;
	box-sizing: border-box;
}
</style>
<script type="text/javascript">
function update(bno){
	//alert("수정");
	if(confirm("수정하시겠습니까?")){
		alert("수정합니다.");
		location.href="update?bno="+bno;
	}
}
function del(bno){
	//alert("삭제");	
	if(confirm("삭제하시겠습니까?")){
		alert("삭제합니다.");
		location.href="delete?bno="+bno;
	}
	
}
</script>
</head>
<body>
<%@ include file="./menu.jsp"%>
	<h1>detail</h1>
	<%
	
	BoardDAO dao = new BoardDAO();
	int bno = Util.str2Int2(request.getParameter("bno"));
	BoardDTO dto = dao.detail(bno);	
	
	
	%>
	bno = <%=bno %>
	

	<hr>
	<div id = "detail">
		<div id = "title"><%=dto.getBtitle() %>
		<%if(session.getAttribute("id") != null && ((String)session.getAttribute("id")).equals(dto.getId())){ %>
		<img alt="delete" src="./delete.png" style="vertical-align: middle;" onclick="return del(<%=dto.getBno() %>)" title="이 글을 삭제 합니다.">

		<img alt="update" src="./update.png" style="vertical-align: middle;" onclick="return update(<%=dto.getBno() %>)" title="이 글을 수정 합니다.">
		<%} %>
		</div>
		<div id = "date">
			<div id = "count"><%=dto.getBcount() %> </div>
			<div id = "date2"><%=dto.getBdate() %> </div>
			<div id = "date2"><%=dto.getName() %>(<%=dto.getId() %>)</div>
		</div>
		<div id="content"><%=dto.getBcontent() %></div>
	</div>	
	
	
	 

	<button onclick="location.href='./board.jsp'">리스트로</button>
	

</body>
</html>

 

반응형