Archive

JSP/Servlet-Servlet 댓글 구현

|

JSP/Servlet - Servlet 댓글 구현


DB를 연동하여 사용자가 글을 남기면 방명록이 남는 댓글 기능을 구현해보자

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 작성하기</title>
</head>
<body>
    <!-- post 방식으로 서블릿에게 데이터 전달 -->
	<form method="post" action="/myWeb/VisitInsert">
		<table align="center" width="500" border="1">
			<tr>
				<th width="70">작성자</th>
			<td width="430">
				&nbsp;<input type="text" name="writer" size="50">
			</td>
			</tr>
			<tr>
			<th>내용</th>
			<td>
				&nbsp;<textarea rows="7" cols="50" name="memo"></textarea>
			</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="저장">&nbsp;&nbsp;
					<input type="reset" value="취소">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>


// 입력을 담당하는 서블릿
import java.io.*;
import java.sql.*
import javax.servlet.*;
import javax.servlet.http.*;

public class VisitInsert extends HttpServlet {
    // 편의상 doGet과 doPost를 한 곳에서 처리   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("utf-8"); //한글처리
    	//client가 http 요청으로 전송한 값 읽기
    	String writer = request.getParameter("writer");
    	String memo = request.getParameter("memo");
    	
        // mysql DB에 HTTP 요청 데이터 저장
    	StringBuffer sql = new StringBuffer();
    	sql.append("insert into visit(writer,memo,regdate)");
    	sql.append("values (?, ?, curdate())");
    	Connection con = null;
    	PreparedStatement pstm = null;
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    		con = DriverManager.getConnection("jdbc:mysql://localhost:3306/visit_db?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false","root","123456");
    		pstm = con.prepareStatement(sql.toString());
    		pstm.setString(1, writer);
    		pstm.setString(2, memo);
    		pstm.executeUpdate();
    	} catch(SQLException e) {
    		e.printStackTrace();
    	} catch(ClassNotFoundException e) {
    		e.printStackTrace();
    	} finally {
    		try {if(pstm != null)pstm.close();}catch(SQLException e) {};
    		try {if(con != null)pstm.close();}catch(SQLException e) {};
    	}
        // submit 후 페이지 이동
    	response.sendRedirect("VisitList");
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


// 웹서버에서 받은 데이터를 화면에 출력하는 서블릿
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class VisitList extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
    	
    	try {
    		out.println("<html>");
    		out.println("<head><title>방명록 리스트</title></head>");
    		out.println("<body>");
    		// DB에서 데이터 조회
    		StringBuffer sql = new StringBuffer();
    		sql.append("select * from visit");
    		Connection con = null;
    		PreparedStatement pstm = null;
    		ResultSet rs = null;
    		
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
    			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/visit_db?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false","root","123456");
        		pstm = con.prepareStatement(sql.toString());
        		rs = pstm.executeQuery();
        		
        		while(rs.next()) {
        			int no = rs.getInt("no");
        			String writer = rs.getString("writer");
        			String memo = rs.getString("memo");
        			java.sql.Date regdate = rs.getDate("regdate");
        			out.println("<table align=center width=500 border=1>");
        			out.println("<tr>");
        			out.println("<th width=50>번호</th>");
        			out.println("<td width=50 align=center>"+no+"</td>");
        			out.println("<th width=70>작성자</th>");
        			out.println("<td width=180 align=center>"+writer+"</td>");
        			out.println("<th width=50>날짜</th>");
        			out.println("<td width=100 align=center>"+regdate+"</td>");
        			out.println("</tr>");
        			out.println("<tr>");
        			out.println("<th width=50>내용</th>");
        			out.println("<td colspan=5>&nbsp;<textarea rows=3 cols=50>"+memo+"</textarea></td>");
        			out.println("</tr>");
        			out.println("</table>");
        			out.println("<p>");
        		}
    		} catch(SQLException e) {
    			e.printStackTrace();
    		} catch(ClassNotFoundException e) {
    			e.printStackTrace();
    		} finally {
    			try {if(pstm != null)pstm.close();}catch(SQLException e) {};
        		try {if(con != null)pstm.close();}catch(SQLException e) {};
    		}
    		out.println("<p align=center><a href=/myWeb/bbs/write.html>글쓰기</a></p>");
    		out.println("</body>");
    		out.println("</html>");
    	} finally {
    		out.close();
    	}
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


실행 화면

실행1 실행2



참고 자료


KG 아이티뱅크 강의 자료