Skip to content

Commit

Permalink
Merge pull request #168 from lass9436/feature7
Browse files Browse the repository at this point in the history
[이영민] step-8 페이징 구현하기
  • Loading branch information
acceptor-gyu authored Aug 6, 2024
2 parents dc9a73e + 31ff3ca commit b28b182
Show file tree
Hide file tree
Showing 13 changed files with 345 additions and 13 deletions.
50 changes: 50 additions & 0 deletions .github/workflows/aws.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Build and Deploy Docker Image

on:
push:
branches:
- lass9436

jobs:
build_and_deploy:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Build Docker image
run: docker build -t jsp-cafe:latest .

- name: Save Docker image to file
run: docker save jsp-cafe:latest | gzip > jsp-cafe.tar.gz

- name: Upload Docker image file
uses: actions/upload-artifact@v3
with:
name: docker-image
path: jsp-cafe.tar.gz

- name: Deploy to EC2
env:
SSH_PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }}
EC2_USER: ${{ secrets.EC2_USER }}
EC2_HOST: ${{ secrets.EC2_HOST }}
run: |
# Save the SSH private key to a file
echo "$SSH_PRIVATE_KEY" > private_key.pem
chmod 600 private_key.pem
# Transfer the Docker image file to EC2 server
scp -i private_key.pem jsp-cafe.tar.gz $EC2_USER@$EC2_HOST:/tmp/
# Connect to EC2 server and run Docker commands
ssh -i private_key.pem $EC2_USER@$EC2_HOST << 'EOF'
docker load < /tmp/jsp-cafe.tar.gz
docker stop jsp-cafe || true
docker rm jsp-cafe || true
docker run -d --name jsp-cafe -p 8080:8080 jsp-cafe:latest
EOF
16 changes: 16 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 빌드 스테이지: Gradle과 JDK 17을 사용하여 WAR 파일 빌드
FROM gradle:7.6.1-jdk17 AS build
WORKDIR /app
COPY . .
RUN ./gradlew clean build

# 실행 스테이지: Tomcat 10.1.26과 JDK 17을 사용하여 WAR 실행
FROM tomcat:10.1.26-jdk17
WORKDIR /usr/local/tomcat/webapps/
COPY --from=build /app/build/libs/*.war ./ROOT.war

# 8080 포트 노출 (Tomcat 기본 포트)
EXPOSE 8080

# Tomcat 실행
CMD ["catalina.sh", "run"]
4 changes: 4 additions & 0 deletions src/main/java/lass9436/comment/model/CommentRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ public interface CommentRepository {
void deleteByCommentSeq(long commentSeq);

List<Comment> findByQuestionSeq(long questionSeq);

List<Comment> findRangeByQuestionSeq(long questionSeq, long startCommentSeq, int count);

long countByQuestionSeq(long questionSeq);
}
46 changes: 46 additions & 0 deletions src/main/java/lass9436/comment/model/CommentRepositoryDBImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,52 @@ public List<Comment> findByQuestionSeq(long questionSeq) {
return comments;
}

@Override
public List<Comment> findRangeByQuestionSeq(long questionSeq, long startCommentSeq, int count) {
String sql = "SELECT * FROM comments WHERE questionSeq = ? AND commentSeq < ? AND useYn = 'Y' ORDER BY commentSeq DESC LIMIT ?";
List<Comment> comments = new ArrayList<>();

try (Connection conn = Database.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {

ps.setLong(1, questionSeq);
ps.setLong(2, startCommentSeq);
ps.setInt(3, count);

try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
comments.add(mapRow(rs));
}
}
} catch (SQLException e) {
e.printStackTrace();
}

return comments;
}

@Override
public long countByQuestionSeq(long questionSeq) {
String query = "SELECT COUNT(*) FROM comments WHERE questionSeq = ? and useYn = 'Y'";
long count = 0;

try (Connection connection = Database.getConnection();
PreparedStatement ps = connection.prepareStatement(query);) {

ps.setLong(1, questionSeq);
ResultSet resultSet = ps.executeQuery();

if (resultSet.next()) {
count = resultSet.getLong(1);
}

} catch (SQLException e) {
e.printStackTrace();
}

return count;
}

private Comment mapRow(ResultSet rs) throws SQLException {
Comment comment = new Comment();
comment.setCommentSeq(rs.getLong("commentSeq"));
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/lass9436/comment/model/CommentRepositoryImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ public void deleteByCommentSeq(long commentSeq) {
commentStore.remove(commentSeq);
}

@Override
public long countByQuestionSeq(long questionSeq) {
return 0;
}

@Override
public List<Comment> findByQuestionSeq(long questionSeq) {
List<Comment> comments = new ArrayList<>();
Expand All @@ -43,5 +48,26 @@ public List<Comment> findByQuestionSeq(long questionSeq) {
}
return comments;
}

@Override
public List<Comment> findRangeByQuestionSeq(long questionSeq, long startCommentSeq, int count) {
List<Comment> result = new ArrayList<>();

// 모든 댓글을 순회하며 조건에 맞는 댓글을 찾습니다.
for (Comment comment : commentStore.values()) {
// 해당 질문의 댓글이고, startCommentSeq보다 작은 commentSeq를 가진 경우
if (comment.getQuestionSeq() == questionSeq && comment.getCommentSeq() < startCommentSeq) {
result.add(comment);
}
}

// commentSeq를 기준으로 내림차순 정렬 (최신 댓글이 먼저 오도록)
result.sort((c1, c2) -> Long.compare(c2.getCommentSeq(), c1.getCommentSeq()));

// count 개수만큼만 반환
return result.stream()
.limit(count)
.toList();
}
}

18 changes: 18 additions & 0 deletions src/main/java/lass9436/comment/servlet/CommentServlet.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lass9436.comment.servlet;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletConfig;
Expand All @@ -23,6 +24,23 @@ public void init(ServletConfig config) throws ServletException {
commentRepository = (CommentRepository)config.getServletContext().getAttribute("commentRepository");
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
long questionSeq = Long.parseLong(req.getParameter("questionSeq"));
long startCommentSeq = Long.parseLong(req.getParameter("startCommentSeq"));
int count = 5; // 또는 req.getParameter("count")로 받아올 수 있습니다.

List<Comment> comments = commentRepository.findRangeByQuestionSeq(questionSeq, startCommentSeq, count);

ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(comments);

resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(jsonResponse);
resp.setStatus(HttpServletResponse.SC_OK);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String contents = req.getParameter("contents");
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/lass9436/config/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

public class Database {

private static final String url = "jdbc:mysql://localhost:3306/jsp_cafe";
private static final String url = "jdbc:mysql://host.docker.internal:3306/jsp_cafe";
private static final String user = "user";
private static final String password = "1234";
private static final MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/lass9436/question/model/QuestionRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ public interface QuestionRepository {
void deleteByQuestionSeq(long questionSeq); // Delete by questionSeq

Question findByTitle(String title); // Read by title

List<Question> findAllPageable(long page, long pageSize);

long count();
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,49 @@ public Question findByTitle(String title) {
return question;
}

@Override
public List<Question> findAllPageable(long page, long pageSize) {
String query = "SELECT * FROM questions WHERE useYn = 'Y' ORDER BY questionSeq DESC LIMIT ? OFFSET ?";
List<Question> questions = new ArrayList<>();

try (Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {

statement.setLong(1, pageSize);
statement.setLong(2, (page - 1) * pageSize);
ResultSet resultSet = statement.executeQuery();

while (resultSet.next()) {
questions.add(mapRowToQuestion(resultSet));
}

} catch (SQLException e) {
e.printStackTrace();
}

return questions;
}

@Override
public long count() {
String query = "SELECT COUNT(*) FROM questions WHERE useYn = 'Y'";
long count = 0;

try (Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
ResultSet resultSet = statement.executeQuery()) {

if (resultSet.next()) {
count = resultSet.getLong(1);
}

} catch (SQLException e) {
e.printStackTrace();
}

return count;
}

private Question mapRowToQuestion(ResultSet resultSet) throws SQLException {
Question question = new Question();
question.setQuestionSeq(resultSet.getLong("questionSeq"));
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/lass9436/question/model/QuestionRepositoryImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,22 @@ public Question findByTitle(String title) {
.findFirst()
.orElse(null);
}

@Override
public List<Question> findAllPageable(long page, long pageSize) {
long startIndex = (page - 1) * pageSize;
return questions.stream()
.filter(q -> "Y".equals(q.getUseYn())) // useYn이 'Y'인 질문만 선택
.sorted((q1, q2) -> Long.compare(q2.getQuestionSeq(), q1.getQuestionSeq())) // questionSeq 내림차순 정렬
.skip(startIndex)
.limit(pageSize)
.toList();
}

@Override
public long count() {
return questions.stream()
.filter(q -> "Y".equals(q.getUseYn())) // useYn이 'Y'인 질문만 카운트
.count();
}
}
23 changes: 21 additions & 2 deletions src/main/java/lass9436/question/servlet/QuestionPageServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,35 @@ private String handleRegister(HttpServletRequest req, HttpServletResponse resp)
}

private String handleList(HttpServletRequest req, HttpServletResponse resp) {
req.setAttribute("questions", questionRepository.findAll());
long page = getPageParameter(req.getParameter("page"));
long pageSize = 15;
req.setAttribute("questions", questionRepository.findAllPageable(page, pageSize));
req.setAttribute("maxPage", (long) Math.ceil((double) questionRepository.count() / pageSize));
return "/list.jsp";
}

private long getPageParameter(String pageParam) {
if (pageParam == null || pageParam.trim().isEmpty()) {
return 1;
}
try {
long page = Long.parseLong(pageParam);
return page > 0 ? page : 1;
} catch (NumberFormatException e) {
return 1;
}
}

private String handleDetail(HttpServletRequest req, HttpServletResponse resp) {
long seq = Long.parseLong(req.getParameter("seq"));
Question question = questionRepository.findByQuestionSeq(seq);
List<Comment> comments = commentRepository.findByQuestionSeq(seq);
List<Comment> comments = commentRepository.findRangeByQuestionSeq(seq, Long.MAX_VALUE, 5);
long lastCommentSeq = !comments.isEmpty() ? comments.get(comments.size() - 1).getCommentSeq() : 0;
long count = commentRepository.countByQuestionSeq(seq);
req.setAttribute("question", question);
req.setAttribute("comments", comments);
req.setAttribute("count", count);
req.setAttribute("lastCommentSeq", lastCommentSeq);
return "/detail.jsp";
}

Expand Down
Loading

0 comments on commit b28b182

Please sign in to comment.