오늘의 코딩순서
(폴더: och16)
메인 페이지 ↓↓↓
http://localhost:8181/och16/list.do
( 줌 강의 0:00~40:00, 1:35~)
- index.jsp(메인 페이지) + ListAction.class (현장 HW1-1) + BoardDao.class (현장 HW1-2)
- list.jsp + ListAction.class + BoardDao.class (현장 HW2)
- content.jsp + ContentAction.class (현장 HW3-1) + BoardDao.class (현장 HW3-2)
오늘의 코딩 포인트
- index.jsp >> 처음 시작하는 메인 페이지
Tip)- 메인 페이지를 만드는 이유
- Controller에서 실행하면 http://localhost:8181/och16/WEB-INF/classes/control/Controller.java주소에서 뒷부분을 수정하고 /list.do 같은 값을 추가해야 하는 번거로움이 있음
메인 페이지 작성 및 실행은 그 번거로움을 줄여줌 - 이 페이지는 jsp라 View는 맞지만 Script 부분을 짜줌으로써, View가 아닌 Controller부터 실행될수 있는 역할을
- Controller에서 실행하면 http://localhost:8181/och16/WEB-INF/classes/control/Controller.java주소에서 뒷부분을 수정하고 /list.do 같은 값을 추가해야 하는 번거로움이 있음
- 메인 페이지를 만드는 이유
<%@ 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>
</head>
<body>
<!-- 아래 세 줄이 Controller를 시작하게 하는 것 -->
<!-- 이렇게 짜두는 것이 Controller 시작 명령을 하나하나 내리는 것보다 효율적임 -->
<script type="text/javascript">
location.href="list.do";
</script>
</body>
</html>
- ListAction.class (현장 HW1-1) ==> Service 모델
Tip)- return⭐⭐
- 여기서 사용한 return은 자바에서 메서드가 실행을 마친 후 호출한 쪽으로 값을 돌려보내는 것을 의미함
- 즉, 메서드가 작업을 끝내고 그 결과를 반환하는 것
- return⭐⭐
package service;
import java.io.IOException;
import java.sql.SQLException;
import dao.BoardDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ListAction implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ListAction Service start...");
//DAO Logic, BoardDao와 연결되는 DAO 로직 짜기
BoardDao bd = BoardDao.getInstance(); //getInstance를 보면 singleton을 연상하기
//(0725)현장 HW1-1
int totCnt;
try {
totCnt = bd.getTotalCnt();
request.setAttribute("totCnt", totCnt);
} catch (SQLException e) {
e.printStackTrace();
//37이 나와야함
}
// view 명칭
// return "listForm.jsp";
return "list.jsp";
}
}
- BoardDao.jsp (현장 HW1-2)
//(0725)현장 HW1-2 => index.jsp와 연결됨
public int getTotalCnt() throws SQLException {
int totCnt = 0;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select count(*) from board";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
if (rs.next()) {
totCnt = rs.getInt(1);
System.out.println("getTotalCnt totCnt->"+totCnt);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
return totCnt;
}
↳ Controller에서 Run(실행) 후 주소 뒤에 /list.do로 바꾸어 리프레시하기
- RE_STEP와 RE_LEVEL에 대하여
- ref : 같은 댓글 그룹
- re step는 같은 댓글 그룹이며 밑의 숫자는 화면에 보이는 입력순서
- re level은 0은 원글, 1은 원글에 대한 댓글, 2는 위 행에 대한 대댓글
- ref : 같은 댓글 그룹
SELECT num,writer,subject,ref,re_step,re_level
FROM board
WHERE ref = 30
ORDER BY ref desc,re_step
- scott_0725_rownum
- rownum
SELECT*
FROM (
SELECT rownum rn, a.*
FROM
(
SELECT *
FROM board
ORDER BY ref desc,re_step
) a
)
WHERE rn BETWEEN 1 AND 10
위와 이어짐
- list.jsp ==> View에 해당함
7.DAO와 DB가 주고받은 결과값이 Controller에 return되어 View가 정해진다
그러나 Controller에 전해지기 전, Service(여기서는 ListAction.class )에서 정해진거나 다름없다
==> ListAction.class에 return 값이 "list.jsp"였기 때문
Tip)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="style.css" type="text/css">
<style type="text/css">
table {
width: 100%;
}
</style>
</head>
<body>
<h1>게시판</h1>
<h3>리스트 개수 : ${totCnt }</h3>
<table>
<tr>
<td><a href="writeForm.do">글쓰기</a></td>
</tr>
<tr>
<th>번호</th><th>제목</th><th>작성자</th><th>이메일</th>
<th>IP</th><th>작성일</th><th>조회수</th>
</tr>
<%-- <c:set var="numbering" value="{(currentPage-1)*10 +1"/> --%>
<c:if test="${totCnt > 0 }">
<c:forEach var="board" items="${list }">
<tr>
<%-- <td>${numbering }</td> --%>
<td>${startNum }</td>
<td class="left" width=200>
<c:if test="${board.readcount > 20 }">
<img src='images/hot.gif' onmouseover="getDeptName(${board.num})">
</c:if>
<c:if test="${board.re_level > 0}">
<img src='images/level.gif' width="${board.re_level*10 }">
<img src='images/re.gif'>
</c:if>
<a href='content.do?num=${board.num}&pageNum=${currentPage}'>
${board.subject}</a>
</td>
<td>${board.writer}</td>
<td><a href="mailto:${board.email }">${board.email }</a></td>
<td>${board.ip}</td>
<td>${board.reg_date}</td>
<td>${board.readcount}</td>
</tr>
<c:set var="startNum" value="${startNum - 1}"/>
<%-- <c:set var="numbering" value="${numbering + 1 }"/> --%>
</c:forEach>
</c:if>
<c:if test="${totCnt == 0}">
<tr>
<td colspan=7>데이터가 없네</td>
</tr>
</c:if>
</table>
<div style="text-align: center;">
<c:if test="${startPage > blockSize }">
<a href='list.do?pageNum=${startPage-blockSize}'>[이전]</a>
</c:if>
<c:forEach var="i" begin="${startPage }" end="${endPage }">
<a href='list.do?pageNum=${i}'>[${i}]</a>
</c:forEach>
<c:if test="${endPage < pageCnt }">
<a href='list.do?pageNum=${startPage+blockSize}'>[다음]</a>
</c:if>
</div>
</body>
</html>
- ListAction.class ==> Service 모델 >> 페이지 번호 누르면 다음 페이지로 넘어가게 하는 로직
package service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import dao.Board;
import dao.BoardDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ListAction implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ListAction Service start...");
//DAO Logic, BoardDao와 연결되는 DAO 로직 짜기
BoardDao bd = BoardDao.getInstance(); //getInstance를 보면 singleton을 연상하기
//(0725)현장 HW1-1
int totCnt;
try {
totCnt = bd.getTotalCnt();
System.out.println("ListAction totCnt->"+totCnt);
String pageNum = request.getParameter("pageNum");
if (pageNum == null || pageNum.equals("")) { pageNum = "1"; }
int currentPage = Integer.parseInt(pageNum); // 1
int pageSize = 10, blockSize = 10;
int startRow = (currentPage - 1) * pageSize +1; // 1 11
int endRow = startRow + pageSize -1; //10 20
int startNum = totCnt - startRow + 1;
//Board조회 1행부터 10행까지
List<Board> list = bd.boardList(startRow,endRow);
// 38 / 10 = 4페이지까지 나옴
int pageCnt = (int)Math.ceil((double)totCnt/pageSize);
// 1
int startPage = (int)(currentPage-1)/blockSize * blockSize + 1; //1
//startPage를 10단위로 매기기 위해
int endPage = startPage + blockSize -1; //10
// 공갈 Page 방지 10 > 4
if (endPage > pageCnt) endPage = pageCnt; //4
request.setAttribute("list", list); ///중요함!!!
request.setAttribute("totCnt", totCnt); ///중요함!!!
request.setAttribute("pageNum", pageNum);
request.setAttribute("currentPage",currentPage );
request.setAttribute("startNum", startNum);
request.setAttribute("blockSize", blockSize);
request.setAttribute("pageCnt", pageCnt);
request.setAttribute("startPage", startPage);
request.setAttribute("endPage", endPage);
} catch (SQLException e) {
e.printStackTrace();
//38이 나와야함
}
// view 명칭
// return "listForm.jsp";
return "list.jsp";
}
}
- BoardDao.class
//(0725)현장 HW2 => list.jsp와 연결됨
public List<Board> boardList(int startRow, int endRow) throws SQLException {
List<Board> list = new ArrayList<Board>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// String sql =
// mysql select * from board by num desc limit startPage 1,-10;
String sql = " SELECT * "
+ " FROM (Select rownum rn ,a.* "
+ " From (select * from board order by ref desc,re_step) a )"
+ " WHERE rn BETWEEN ? AND ? " ;
System.out.println("boardList sql->"+sql);
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, startRow);
pstmt.setInt(2, endRow);
rs = pstmt.executeQuery();
while (rs.next()) {
Board board = new Board();
board.setNum(rs.getInt("num"));
board.setWriter(rs.getString("writer"));
board.setSubject(rs.getString("subject"));
board.setEmail(rs.getString("email"));
board.setReadcount(rs.getInt("readcount"));
board.setIp(rs.getString("ip"));
board.setRef(rs.getInt("ref"));
board.setRe_level(rs.getInt("re_level"));
board.setRe_step(rs.getInt("re_step"));
board.setReg_date(rs.getDate("reg_date"));
list.add(board);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
return list;
}
- content.jsp ==> View에 해당함
<%@ 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="style.css" type="text/css">
<style type="text/css">
table {
width: 80%;
}
</style>
</head>
<body>
<table border="1">
<caption><h2>게시판 상세내역${num }</h2></caption>
<tr> <td width="50">번호</td><td>${board.num}</td> </tr>
<tr> <td>제목</td> <td>${board.subject}</td> </tr>
<tr> <td>작성자</td> <td>${board.writer}</td> </tr>
<tr> <td>작성일</td> <td>${board.reg_date}</td> </tr>
<tr> <td>조회수</td> <td>${board.readcount}</td> </tr>
<tr> <td>IP</td> <td>${board.ip}</td> </tr>
<tr> <td>이메일</td> <td>${board.email}</td> </tr>
<tr> <td>내용</td> <td>${board.content}</td> </tr>
<tr><td colspan="2">
<input type="button" value="수정"
onclick="location.href='updateForm.do?num=${board.num}&pageNum=${pageNum}'">
<input type="button" value="답변작성"
onclick="location.href='writeForm.do?num=${board.num}&pageNum=${pageNum}'">
<input type="button" value="삭제"
onclick="location.href='deleteForm.do?num=${board.num}&pageNum=${pageNum}'">
<input type="button" value="목록"
onclick="location.href='list.do?pageNum=${pageNum}'">
</td></tr>
</table>
</body>
</html>
- ContentAction.class ==> Service 모델
package service;
import java.io.IOException;
import java.sql.SQLException;
import dao.Board;
import dao.BoardDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ContentAction implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ContentAction Service start...");
//(0725)현장 HW3-1
// 1. num , pageNum Get
int num = Integer.parseInt(request.getParameter("num"));
String pageNum = request.getParameter("pageNum");
// DAO Logic
try {
// 2. BoardDao bd Instance
BoardDao bd = BoardDao.getInstance();
// 3. num의 readCount 증가
//bd.readCount(num);
// 4. Board board = bd.select(num);
Board board = bd.select(num);
// 5. request 객체에 num , pageNum , board
request.setAttribute("num", num);
request.setAttribute("pageNum", pageNum);
request.setAttribute("board", board);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
// 6. view 명칭
return "content.jsp";
}
}
- BoardDao.class
//(0725)현장 HW3-2= > content.jsp와 연결됨
// DAO Logic
// 2. BoardDao bd Instance
// 3. Board board = bd.select(num);
public Board select(int num) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from board where num="+num;
//num은 primary key
Board board = new Board();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()) {
//primary가 확실하게 정해져 있으므로 오류가능성이 있는 while보다는 if문 사용
board.setNum(rs.getInt("num"));
board.setWriter(rs.getString("writer"));
board.setSubject(rs.getString("subject"));
board.setContent(rs.getString("content"));
board.setEmail(rs.getString("email"));
board.setReadcount(rs.getInt("readcount"));
board.setIp(rs.getString("ip"));
System.out.println("select ip->"+rs.getString("ip"));
board.setReg_date(rs.getDate("reg_date"));
System.out.println("select reg_date->"+rs.getDate("reg_date"));
board.setRef(rs.getInt("ref"));
board.setRe_level(rs.getInt("re_level"));
board.setRe_step(rs.getInt("re_step"));
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
return board;
}
readcount 오르도록 ContentAction.class와 BoardDao.class에 로직 추가>> 클릭할때마다 조회수가 오르는 로직
- ContentAction.class ==> View에 해당함
package service;
import java.io.IOException;
import java.sql.SQLException;
import dao.Board;
import dao.BoardDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ContentAction implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ContentAction Service start...");
//(0725)현장 HW3-1
// 1. num , pageNum Get
int num = Integer.parseInt(request.getParameter("num"));
String pageNum = request.getParameter("pageNum");
// DAO Logic
try {
// 2. BoardDao bd Instance
BoardDao bd = BoardDao.getInstance();
//(0725)현장 HW3-3
// 3. num의 readCount 증가
//bd.readcount(num);
bd.readcount(num);
// 4. Board board = bd.select(num);
Board board = bd.select(num);
// 5. request 객체에 num , pageNum , board
request.setAttribute("num", num);
request.setAttribute("pageNum", pageNum);
request.setAttribute("board", board);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
// 6. view 명칭
return "content.jsp";
}
}
- BoardDao.class
Tip)
- void로 설정한 이유:
//(0725)현장 HW3-4 => content.jsp와 연결됨
public void readcount(int num) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set readcount=readcount+1 where num=?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
//void는 return 값이 없다
}
질문목록
수업교재
오늘의 숙제
'JSP > Java Script' 카테고리의 다른 글
2024_07_26_금 (0) | 2024.07.26 |
---|---|
2024_07_24_수 (0) | 2024.07.24 |
2024_07_23_화~ 07_24_수 (0) | 2024.07.23 |
2024_07_22_월 (0) | 2024.07.22 |
2024_07_19_금 ⭐⭐⭐ (0) | 2024.07.19 |