Servlet
--HTML코드 출력 문제--> JSP
--스파게티 코드 문제--> [JSP MVC
] -> Spring MVC
-> SpringBoot
코드 블럭을 사용에서 게시글 리스트를 구현해보았다. 이런 방식을 이용해서 실제 데이터를 집어 넣어보겠다.
list.jsp
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; UTF-8" %>
<%
String url = "jdbc:mysql://localhost:3306/newlecture";
String sql = "select * from notice";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
~~~
<% while(rs.next()) {%>
<tr>
<td><%=rs.getInt("id")%></td>
<td class="title indent text-align-left"><a href="detail.html"><%=rs.getString("title")%></a></td>
<td><%=rs.getString("memberID")%></td>
<td>
<%=rs.getDate("regDate")%>
</td>
<td><%=rs.getInt("hit")%></td>
</tr>
<%}%>
~~~
<%
rs.close();
st.close();
con.close();
%>
WEB-INF/lib
디렉토리에 mysql-connector-java-8.0.xx.jar
파일을 넣어준다.WEB-INF/lib
에 추가해준다.결과는
list.jsp에서 글 제목을 클릭하면 상세 페이지로 연결되게끔
list.jsp
<td class="title indent text-align-left">
<a href="detail.jsp?id=<%=rs.getInt("id")%>"><%=rs.getString("title")%>
</a>
</td>
수정하고
detail.jsp
<%@ page import="java.sql.*" %>
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; UTF-8" %>
<%
int id = Integer.parseInt(request.getParameter("id"));
String url = "jdbc:mysql://localhost:3306/newlecture";
String sql = "select * from notice where id=?";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "991911");
PreparedStatement st = con.prepareStatement(sql);
st.setInt(1, id);
ResultSet rs = st.executeQuery();
rs.next();
%>
~~~
<tbody>
<tr>
<th>제목</th>
<td class="text-align-left text-indent text-strong text-orange" colspan="3"><%=rs.getString("title")%></td>
</tr>
<tr>
<th>작성일</th>
<td class="text-align-left text-indent" colspan="3"><%=rs.getDate("regDate")%></td>
</tr>
<tr>
<th>작성자</th>
<td><%=rs.getString("memberID")%></td>
<th>조회수</th>
<td><%=rs.getString("hit")%></td>
</tr>
<tr>
<th>첨부파일</th>
<td colspan="3"><%=rs.getString("files")%></td>
</tr>
<tr class="content">
<td colspan="4"><%=rs.getString("content")%></td>
</tr>
</tbody>
<%
rs.close();
st.close();
con.close();
%>
list.jsp에서의 Statement 객체 대신 PreparedStatement 객체를 사용
detail.jsp?id=<%=rs.getInt("id")%>
에서 넘어온 id를 SQL문 select * from notice where id =?
에
setInt(1,id)
로 심어준다.
현재 list.jsp와 detail.jsp는 모두 앞서 언급했던 스파게티 코드 문제가 발생할 수 있기에
JSP MVC model1 방식으로 바꾸어주자.
list.jsp는 model2만
detail.jsp
<%@ page import="java.sql.*" %>
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; UTF-8" %>
<%
int id = Integer.parseInt(request.getParameter("id"));
String url = "jdbc:mysql://localhost:3306/newlecture";
String sql = "select * from notice where id=?";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "991911");
PreparedStatement st = con.prepareStatement(sql);
st.setInt(1, id);
ResultSet rs = st.executeQuery();
rs.next();
String title = rs.getString("title");
Date regDate = rs.getDate("regDate");
int memberID = rs.getInt("memberID");
int hit = rs.getInt("hit");
String files = rs.getString("files");
String content = rs.getString("content");
rs.close();
st.close();
con.close();
%>
~~~
<tbody>
<tr>
<th>제목</th>
<td class="text-align-left text-indent text-strong text-orange" colspan="3"><%=title%></td>
</tr>
<tr>
<th>작성일</th>
<td class="text-align-left text-indent" colspan="3"><%=regDate%></td>
</tr>
<tr>
<th>작성자</th>
<td><%=memberID%></td>
<th>조회수</th>
<td><%=hit%></td>
</tr>
<tr>
<th>첨부파일</th>
<td colspan="3"><%=files%></td>
</tr>
<tr class="content">
<td colspan="4"><%=content%></td>
</tr>
</tbody>
jsp 파일 상단에 Controller 부분을 모아 변수로서 값들을 할당하고
출력 코드에 변수들만을 할당했다.
우리가 배운 것은 JSP MVC model2 방식도 있다.
- `Notice***Controller`라는 Servlet을 만들어 ***.jsp로 forward시켜주는 방식으로 구현
- request객체에 내용들을 담아서 forward
- jsp 파일 내에 코드 블럭 대신 EL 사용
NoticeListController.java
@WebServlet("/notice/list")
public class NoticeListController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "jdbc:mysql://localhost:3306/newlecture";
String sql = "select * from notice";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "991911");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
List<Notice> noticeList = new ArrayList<>();
while (rs.next()) {
Notice notice = new Notice(
rs.getInt("id"),
rs.getString("title"),
rs.getString("content"),
rs.getDate("regDate"),
rs.getInt("memberID"),
rs.getString("files"),
rs.getInt("hit"),
rs.getInt("pub")
);
noticeList.add(notice);
}
request.setAttribute("noticeList", noticeList);
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/notice/list.jsp");
dispatcher.forward(request, response);
}
}
list.jsp
<% List<Notice> noticeList = (List<Notice>) request.getAttribute("noticeList");
for(Notice n : noticeList) {
pageContext.setAttribute("n",n);%>
<tr>
<td>${n.id}</td>
<td class="title indent text-align-left"><a href="detail?id=${n.id}">${n.title}</a></td>
<td>${n.memberID}</td>
<td>
${n.regDate}
</td>
<td>${n.hit}</td>
</tr>
<%}%>
for문을 도는 방법은 배우지 않았기에 for문 로직은 코드 블럭을 이용했다.
NoticeDetailController.java
@WebServlet("/notice/detail")
public class NoticeDetailController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String url = "jdbc:mysql://localhost:3306/newlecture";
String sql = "select * from notice where id=?";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "991911");
PreparedStatement st = con.prepareStatement(sql);
st.setInt(1, id);
ResultSet rs = st.executeQuery();
rs.next();
String title = rs.getString("title");
Date regDate = rs.getDate("regDate");
int memberID = rs.getInt("memberID");
int hit = rs.getInt("hit");
String files = rs.getString("files");
String content = rs.getString("content");
int pub = rs.getInt("pub");
Notice notice = new Notice(id, title, content, regDate, memberID, files, hit, pub);
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/notice/detail.jsp");
dispatcher.forward(request, response);
}
}
detail.jsp
<table class="table">
<tbody>
<tr>
<th>제목</th>
<td class="text-align-left text-indent text-strong text-orange" colspan="3">${notice.title}</td>
</tr>
<tr>
<th>작성일</th>
<td class="text-align-left text-indent" colspan="3">${notice.regDate}</td>
</tr>
<tr>
<th>작성자</th>
<td>${notice.memberID}</td>
<th>조회수</th>
<td>${notice.hit}</td>
</tr>
<tr>
<th>첨부파일</th>
<td colspan="3">${notice.files}</td>
</tr>
<tr class="content">
<td colspan="4">${notice.content}</td>
</tr>
</tbody>
</table>