본문 바로가기

웹 - JDBC

웹 - jdbc - 예제(방명록2) - 방명록 꾸미기/글 추가 기능

파일의 기능과 구성

 

방명록 꾸미기

)jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- JSTL Library  -->
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>   
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<%--현재 컨텍스트 경로 : ${ pageContext.request.contextPath  }--%>
<link rel="stylesheet" href="../css/visit.css">

</head>
<body>
<div id="box">
	<h1 id="title">::::: 방명록 :::::</h1>
			
	<div style="margin-bottom: 10px">
		<input class="btn btn-primary"  type="button" value="글쓰기"
				onclick="location.href='insert_form.do'">
	</div>
	
	<!-- 내용이 없을 경우 -->
	<c:if test="${ empty requestScope.list }">
		<div id="empty_msg">등록된 게시물이 없습니다</div>
	</c:if>
	
	<!-- 내용 -->
	<!-- for(VisitVo vo : list) 동일 -->
	<c:forEach var="vo" items="${ requestScope.list }">
	<!-- 코드 정렬 : ctrl + shift + f -->
		<form class="form-inline">
			<div class="panel panel-primary">
				<div class="panel-heading">
					<h4><b>${ vo.name }</b>님의 글:</h4>
				</div>
				<div class="panel-body">
					<div class="mycommon content">${ vo.content }</div>
					<div class="mycommon regdate">작성일자 : ${ fn:substring(vo.regdate,0,16) }</div>
					<div class="mycommon pwd">
						비밀번호 : <input class="form-control" type="password" id="pwd">
								<input class="btn btn-success" type="button" value="수정">
								<input class="btn btn-danger" type="button" value="삭제">
					</div>
				</div>
			</div>
		</form>	
	</c:forEach>
	
</div>

</body>
</html>

 

)css

@charset "UTF-8";

#box{
	width: 700px;
	margin: auto;	/* 중앙정렬 */
	margin-top: 30px;
	
}

#title {
	
	text-align: center;
	font-size: 28px;
	font-weight: bold;
	
	color: #004080;
	
	text-shadow: 1px 1px 1px black;	
	
	margin-bottom: 60px;
}


#empty_msg {
	
	text-align: center;
	color: red;
	font-weight: bold;
	font-size: 20px;
	
	margin-top: 80px;
	
}

.mycommon {
	margin: 5px;
	padding: 5px;
	border: 1px solid #cccccc;
	box-shadow: 1px 1px 1px #666666;
}

.content {
	
	min-height: 60px;
	
	font-size: 16px;
}

.regdate , .pwd {
	font-weight: bold;
}

 

)(글쓰기)추가 폼 만들기 VisitInsertFormAction

package action;

import jakarta.servlet.RequestDispatcher;
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;

/**
 * Servlet implementation class VisitInsertFormAction
 */
@WebServlet("/visit/insert_form.do")
public class VisitInsertFormAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// Dispatcher형식으로 호출
		String forward_page = "visit_insert_form.jsp";
		RequestDispatcher disp = request.getRequestDispatcher(forward_page);
		disp.forward(request, response);

	}

}

 

visit_insert_form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">
	#box{
		width: 600px;
		margin: auto;
		margin-top: 100px;
		
	}
	
	textarea {
		resize: none;
	}
	
	th {
		width: 15%;
		vertical-align: middle !important;
	}
</style>

<script type="text/javascript">
	function send(f) {
		
		//입력값 검증
		let name	= f.name.value.trim();
		let content = f.content.value.trim();
		let pwd		= f.pwd.value.trim();
		
		if(name=='') {
			alert('작성자명을 입력하시오.');
			f.name.value = "";
			f.name.focus();
			return;
		}
		if(content=='') {
			alert('내용을 입력하시오.');
			f.content.value = "";
			f.content.focus();
			return;
		}
		if(pwd=='') {
			alert('비밀번호를 입력하시오.');
			f.pwd.value = "";
			f.pwd.focus();
			return;
		}
		
		f.method = "post";
		f.action = "insert.do"; // 전송대상
		f.submit();	// 전송
	}

</script>

</head>
<body>
	
	<form>
		<div id="box">
		<!-- 코드 정렬 : ctrl + shift + f -->
			<div class="panel panel-primary">
				<div class="panel-heading"><h4>글쓰기</h4></div>
				<div class="panel-body">
					
					<table class="table">
						<tr>
							<th>작성자</th>
							<td><input class="form-control" name="name" required="required"></td>
						</tr>
						
						<tr>
							<th>내용</th>
							<td>
								<textarea class="form-control" rows="6" name="content"></textarea>
							</td>
						</tr>
						
						<tr>
							<th>비밀번호</th>
							<td><input class="form-control" name="pwd" type="password"></td>
						</tr>
						
						<tr>
							<td colspan="2" align="center">
								<input class="btn btn-success" type="button" value="목록보기" 
									   onclick="location.href='list.do'">
								<input class="btn btn-primary" type="button" value="글올리기"
										onclick="send(this.form);">
							</td>
						</tr>
						
					</table>
				</div>
			</div>
		</div>
	</form>
	
</body>
</html>

 

)글 추가 서블릿 VisitInsertAction

package action;

import java.io.IOException;

import dao.VisitDao;
import db.vo.VisitVo;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class VisitInsertAction
 */
@WebServlet("/visit/insert.do")
public class VisitInsertAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(
			HttpServletRequest request, // client -> server로 들어오는 정보처리
			HttpServletResponse response) // server -> client로 들어오는 정보처리
			throws ServletException, IOException {

		// /visit/insert.do?name=홍길동&content=ㅋㅋ&pwd=1234
		
		// 0.수신인코딩 설정
		request.setCharacterEncoding("utf-8");
		
		// 1.parameter(전달인자) 받기
		String name = request.getParameter("name");
		String content = request.getParameter("content");
		String pwd = request.getParameter("pwd");
		
		// 2. ip정보 얻어온다
		String ip = request.getRemoteAddr();
		
		// 3. VisitVo 포장
		// vo에서 생성자 추가하기
		// VisitVo vo = new  VisitVo();
		// vo.set..(); 의 과정 생략
		VisitVo vo = new VisitVo(name, content, pwd, ip);
		
		// 4. DB insert
		int res = VisitDao.getInstance().insert(vo); // dao클래스에 메서드 추가
			
	}

}

 

 

)dao의 insert()

public int insert(VisitVo vo) {
    // TODO Auto-generated method stub

    int res = 0;
    Connection conn = null;
    PreparedStatement pstmt = null;
    //                                                           1 2 3 4 <- pstmt index
    String sql = "insert into visit values(seq_visit_idx.nextVal,?,?,?,?,sysdate)";

    try {
        //1.Connection 얻어오기
        conn = DBService.getInstance().getConnection();

        //2.PreparedStatement
        pstmt = conn.prepareStatement(sql);

        //3.pstmt parameter index 채우기
        pstmt.setString(1, vo.getName());
        pstmt.setString(2, vo.getContent());
        pstmt.setString(3, vo.getPwd());
        pstmt.setString(4, vo.getIp());
        //4.DB insert
        res = pstmt.executeUpdate();

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

    } finally {

        //마무리 작업(열린역순으로 닫기)
        try {
            if (pstmt != null)
                pstmt.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return res;

}//end:insert()

 

-> 다시 서블릿 VisitInsertAction

// 5. 목록보기 이동

response.sendRedirect("list.do"); // 이미 같은 경로이기 때문에 /visit를 추가할 필요 없다.