JSP - 리스트, 상세페이지 구현

RYU·2025년 5월 18일

JSP

목록 보기
1/5

LIST

servlet

@WebServlet("/article/list")
public class ArticleListServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		// DB 연결
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("클래스 x");
			e.printStackTrace();

		}

		String url = "jdbc:mysql://127.0.0.1:3306/AM_JSP_25_04?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul";
		String user = "root";
		String password = "";

		Connection conn = null;

		try {
			conn = DriverManager.getConnection(url, user, password);
			response.getWriter().append("연결 성공!");

			// DBMS에서 article 불러오기
			SecSql sql = SecSql.from("SELECT *");
			sql.append("FROM article");
			sql.append("ORDER BY id DESC;");

			// 정보 저장
			List<Map<String, Object>> articleRows = DBUtil.selectRows(conn, sql);

			// setAttribute() : 지정된 요소의 속성 값을 설정 
			request.setAttribute("articleRows", articleRows);

			request.getRequestDispatcher("/jsp/article/list.jsp").forward(request, response);

		} catch (SQLException e) {
			System.out.println("에러 1 : " + e);
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

}

jsp

// 이게 있어야 리스트를 불러올 수 있다.
<%
List<Map<String, Object>> articleRows = (List<Map<String, Object>>) request.getAttribute("articleRows");
%>


<tbody>
			<%
			for (Map<String, Object> articleRow : articleRows) {
			%>
			<tr style="text-align: center;">
				<td><%=articleRow.get("id")%>번</td>
				<td><%=articleRow.get("regDate")%></td>
				<td><%=articleRow.get("title")%></td>
				<td><%=articleRow.get("body")%></td>
			</tr>
			<%
			}
			%>
		</tbody>
  • map형식의 articleRow를 articleRows까지 순회하면서 'id, regDate,title,body'를 다 가져와 리스트에 모두 나오게 만든다.

DETAIL

servlet


			// 내가 원하는 정보의 상세페이지를 보기 위해서는 id가 필요
			int id = Integer.parseInt(request.getParameter("id"));

			SecSql sql = SecSql.from("SELECT *");
			sql.append("FROM article");
			sql.append("WHERE id = ?;", id);

			Map<String, Object> articleRow = DBUtil.selectRow(conn, sql);

			request.setAttribute("articleRow", articleRow);

			request.getRequestDispatcher("/jsp/article/detail.jsp").forward(request, response);

jsp

<%
Map<String, Object> articleRow = (Map<String, Object>) request.getAttribute("articleRow");
%>

<title>게시글 상세페이지</title>
</head>
<body>

	<h2>게시글 상세페이지</h2>


	<div>
		번호 :
		<%=articleRow.get("id")%></div>
	<div>
		날짜 :
		<%=articleRow.get("regDate")%></div>
	<div>
		제목 :
		<%=articleRow.get("title")%></div>
	<div>
		내용 :
		<%=articleRow.get("body")%></div>


	<div>
		<a style="color: green;" href="list">리스트로 돌아가기</a>
	</div>
	<a style="color: green;" href="../home/main">메인으로 이동</a>

</body>

0개의 댓글