Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4주차 미션 / 서버 4조 배준영 #48

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
ba5ade9
feat: html to jsp 변경 & HomeController 구현
kwiyoon Mar 25, 2024
feded75
rename: html to jsp 모두 변경
kwiyoon Mar 25, 2024
a5b7f92
refactor: jsp 중복 제거
kwiyoon Mar 26, 2024
a655cd0
feat: 개인정보 수정 구현
kwiyoon Mar 26, 2024
1704137
feat: 로그인, 로그아웃 구현
kwiyoon Mar 26, 2024
1766636
feat: 개인정보 보안 강화 구현
kwiyoon Mar 26, 2024
9c6aa01
feat: mvc framwork 구현 및 적용
kwiyoon Mar 26, 2024
b6b32b3
docs: update README.md
kwiyoon Mar 27, 2024
44527ef
rename(RequestMapping)
kwiyoon Apr 1, 2024
dbde550
featr: qna 관련 jsp 파일 수정
kwiyoon Apr 5, 2024
a801a7c
feat: Answer, Question 구현
kwiyoon Apr 5, 2024
129ef35
feat: qna 비동기 통신 & JSON 반환 로직 구현
kwiyoon Apr 5, 2024
50b5def
Feat: ModelAndView,View 객체 구현
junyoungBae1 Apr 7, 2024
9bb0b4d
Feat: Controller에 ModelAndView 적용
junyoungBae1 Apr 9, 2024
bc28811
Fix: Answer 객체를 Json 구조에 맞게 수정
junyoungBae1 Apr 10, 2024
a54bb5c
Feat: AbstractController생성 및 controller에 적용
junyoungBae1 Apr 12, 2024
c03d457
Refactor: view model parameter type 변환
junyoungBae1 Apr 12, 2024
b666906
Refactor: Controller의 resp삭제
junyoungBae1 Apr 12, 2024
282fb5d
Refactor: Controller의 req를 params로 변경
junyoungBae1 Apr 12, 2024
facb6a4
Refactor: ModelAndView 메소드 체이닝 적용
junyoungBae1 Apr 12, 2024
1ad1d4e
Fix: 오류 수정
junyoungBae1 Apr 12, 2024
8624fa5
Style: 불필요한 import 제거
junyoungBae1 Apr 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# KUIT3_java-webMVC
KUIT 3기 서버 파트 - 3, 4주차 미션 레포지토리

### 미션 제출 PR 시, 구현한 내용에 대해 작성해주시기 바랍니다!

전부 미션을 완료하지 못해도 괜찮습니다.

하지만, 어느정도 구현이 되었는지를 알아야 전반적인 강의 난이도를 조절할 수 있고, 코드 리뷰를 원활히 할 수 있기에 꼭꼭 본인이 한 내용에 대해 정리 부탁드립니다!
54 changes: 54 additions & 0 deletions src/main/java/core/db/MemoryAnswerRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package core.db;

import jwp.model.Answer;
import jwp.model.Question;

import java.util.*;

public class MemoryAnswerRepository {
private Map<Long, Answer> answers = new HashMap<>();
private static MemoryAnswerRepository memoryAnswerRepository;
private static Long id = 0L;

private MemoryAnswerRepository() {
addAnswer(new Answer(0L, "김한주", "나도 궁금해요"));
addAnswer(new Answer(0L, "강지윤", "시홍쓰 확장해주세요."));
addAnswer(new Answer(0L, "이현희", "이 편지는 쿠잇에서 최초로 시작되어 일년에 한바퀴를 돌면서 받는 사람에게 행운을 주었고 지금은 당신에게로 옮겨진 이 편지는 4일 안에 당신 곁을 떠나야 합니다. 이 편지를 포함해서 7통을 행운이 필요한 사람에게 보내 주셔야 합니다. 복사를 해도 좋습니다. 혹 미신이라 하실지 모르지만 사실입니다. 쿠잇의 nooyij이라는 사람은 1930년에 이 편지를 받았습니다. 그는 ai 비서 chat GPT에게 복사해서 보내라고 했습니다. 며칠 뒤에 복권이 당첨되어 20억을 받고싶다. 어떤 이는 이 편지를 받았으나 96시간 이내 자신의 손에서 떠나야 한다는 사실을 잊었습니다. 그는 곧 5out이 되었습니다. 나중에야 이 사실을 알고 7통의 편지를 보냈는데 다시 기회를 얻었습니다. 이 편지를 버리거나 낙서를 해서는 절대로 안됩니다. 7통입니다. 이 편지를 받은 사람은 행운이 깃들것입니다. 힘들겠지만 좋은게 좋다고 생각하세요. 7년의 행운을 빌면서..."));
addAnswer(new Answer(1L, "강지윤", "제 글에도 이 댓 다셨던데, 저 벌써 70번째 공유중입니다. 그만해주십시오."));
}

public static MemoryAnswerRepository getInstance() {
if (memoryAnswerRepository == null) {
memoryAnswerRepository = new MemoryAnswerRepository();
return memoryAnswerRepository;
}
return memoryAnswerRepository;
}

private Long generateId(){
return id++;
}

// 내부 저장을 위한 메서드
private void addAnswer(Answer answer) {
Long newId = generateId();
answer.setAnswerId(newId);
Question question = MemoryQuestionRepository.getInstance().findQuestionById(answer.getQuestionId());
question.increaseCountOfAnswer();
answers.put(newId, answer);
}

public Answer insert(Answer answer) {
Long newId = generateId();
answer.setAnswerId(newId);
answers.put(newId,answer);
return answer;
}

public List<Answer> findAnswersByQuestionId(Long quesionId) {
return answers.values().stream()
.filter(answer -> Objects.equals(answer.getQuestionId(), quesionId))
.toList();
}

}
56 changes: 56 additions & 0 deletions src/main/java/core/db/MemoryQuestionRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package core.db;

import jwp.model.Question;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MemoryQuestionRepository {
private Map<Long, Question> questions = new HashMap<>();
private static MemoryQuestionRepository memoryQuestionRepository;
private static Long id = 0L;

private MemoryQuestionRepository() {
addQuestion(new Question("강지윤", "건대 맛집 추천해주세요!!!", "ㅈㄱㄴ"));
addQuestion(new Question("이현희", "5초안에 읽으면 좋은일 일어남", "이 편지는 쿠잇에서 최초로 시작되어 일년에 한바퀴를 돌면서 받는 사람에게 행운을 주었고 지금은 당신에게로 옮겨진 이 편지는 4일 안에 당신 곁을 떠나야 합니다. 이 편지를 포함해서 7통을 행운이 필요한 사람에게 보내 주셔야 합니다. 복사를 해도 좋습니다. 혹 미신이라 하실지 모르지만 사실입니다. 쿠잇의 nooyij이라는 사람은 1930년에 이 편지를 받았습니다. 그는 ai 비서 chat GPT에게 복사해서 보내라고 했습니다. 며칠 뒤에 복권이 당첨되어 20억을 받고싶다. 어떤 이는 이 편지를 받았으나 96시간 이내 자신의 손에서 떠나야 한다는 사실을 잊었습니다. 그는 곧 5out이 되었습니다. 나중에야 이 사실을 알고 7통의 편지를 보냈는데 다시 기회를 얻었습니다. 이 편지를 버리거나 낙서를 해서는 절대로 안됩니다. 7통입니다. 이 편지를 받은 사람은 행운이 깃들것입니다. 힘들겠지만 좋은게 좋다고 생각하세요. 7년의 행운을 빌면서..."));
}

public static MemoryQuestionRepository getInstance() {
if (memoryQuestionRepository == null) {
memoryQuestionRepository = new MemoryQuestionRepository();
return memoryQuestionRepository;
}
return memoryQuestionRepository;
}

private Long generateId(){
return id++;
}

public void addQuestion(Question question) {
Long newId = generateId();
question.setQuestionId(newId);
questions.put(newId, question);
}

public Question findQuestionById(Long questionId) {
return questions.get(questionId);
}

public Collection<Question> findAll() {
return questions.values();
}

public void update(Question question){
if (questions.get(question.getQuestionId()) != null)
questions.put(question.getQuestionId(), question);
}

public void updateQuestionContent(Question question) {
if (questions.get(question.getQuestionId()) != null)
questions.put(question.getQuestionId(), question);
}


}
3 changes: 3 additions & 0 deletions src/main/java/core/db/MemoryUserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ public class MemoryUserRepository {
private static MemoryUserRepository memoryUserRepository;

private MemoryUserRepository() {
addUser(new User("jiyoon","jiyoon","지윤","[email protected]"));
addUser(new User("jiyoon2","jiyoon2","지윤이","[email protected]"));
addUser(new User("admin","admin","어드민","[email protected]"));
}

public static MemoryUserRepository getInstance() {
Expand Down
11 changes: 0 additions & 11 deletions src/main/java/core/db/Repository.java

This file was deleted.

14 changes: 14 additions & 0 deletions src/main/java/core/mvc/AbstractController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package core.mvc;

import core.mvc.view.JsonView;
import core.mvc.view.JspView;

public abstract class AbstractController implements Controller {
protected ModelAndView JspView(String url) {
return new ModelAndView(new JspView(url));
}

protected ModelAndView JsonView() {
return new ModelAndView(new JsonView());
}
}
13 changes: 13 additions & 0 deletions src/main/java/core/mvc/Controller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package core.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

public interface Controller {
ModelAndView execute(Map<String, String> params) throws IOException;

default void setSession(HttpSession httpSession){};
}
41 changes: 41 additions & 0 deletions src/main/java/core/mvc/DispatcherServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package core.mvc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "dispatcher", urlPatterns = "/", loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {

private RequestMapping requestMapping;

@Override
public void init() throws ServletException {
this.requestMapping = new RequestMapping();
}

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Controller controller = requestMapping.getController(req);
controller.setSession(req.getSession());
try {
ModelAndView mav = controller.execute(createParams(req));
mav.render(req,resp);
} catch (Throwable e) {
throw new ServletException(e.getMessage());
}
}

private Map<String, String> createParams(HttpServletRequest request){
Map<String, String> params = new HashMap<>();
request.getParameterNames().asIterator().forEachRemaining(
paramName -> params.put(paramName, request.getParameter(paramName)));
return params;
}

}
20 changes: 20 additions & 0 deletions src/main/java/core/mvc/ForwardController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package core.mvc;

import core.mvc.view.JspView;

import java.util.Map;

public class ForwardController implements Controller {
private String forwardUrl;

public ForwardController(String forwardUrl) {
this.forwardUrl = forwardUrl;
if (forwardUrl == null) {
throw new NullPointerException("forwardUrl is null. 이동할 URL을 입력하세요.");
}
}
@Override
public ModelAndView execute(Map<String, String> params) {
return new ModelAndView(new JspView(forwardUrl));
}
}
36 changes: 36 additions & 0 deletions src/main/java/core/mvc/ModelAndView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package core.mvc;

import core.mvc.view.RedirectView;
import core.mvc.view.View;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class ModelAndView {
View view;
Map<String, Object> model = new HashMap<>();

public ModelAndView(View view){
this.view = view;
}

public ModelAndView addModel(String key, Object val){
model.put(key, val);
return this;
}

public void render(HttpServletRequest req, HttpServletResponse resp) throws Exception {
view.render(model, req, resp);
}

public static ModelAndView redirect(String redirectUrl) {
return new ModelAndView(new RedirectView(redirectUrl));
}

public Map<String, Object> getModel() {
return model;
}

}

41 changes: 41 additions & 0 deletions src/main/java/core/mvc/RequestMapping.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package core.mvc;

import jwp.controller.*;
import jwp.controller.qna.ShowQuestionController;
import jwp.controller.qna.api.AddAnswerController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class RequestMapping {
private Map<String , Controller> controllers = new HashMap<>();

public RequestMapping() {
initControllers();
}

private void initControllers() {
controllers.put("/", new HomeController());

controllers.put("/user/form", new ForwardController("/user/form.jsp"));
controllers.put("/user/loginForm", new ForwardController("/user/login.jsp"));
controllers.put("/user/loginFailed", new ForwardController("/user/login_failed.jsp"));


controllers.put("/user/userList", new ListUserController());
controllers.put("/user/login", new LogInController());
controllers.put("/user/logout", new LogOutController());
controllers.put("/user/signup", new CreateUserController());
controllers.put("/user/updateForm", new UpdateUserFormController());
controllers.put("/user/update", new UpdateUserController());

controllers.put("/qna/form", new ForwardController("/qna/form.jsp"));
controllers.put("/qna/show", new ShowQuestionController());
controllers.put("/api/qna/addAnswer", new AddAnswerController());
}

public Controller getController(HttpServletRequest request) {
return controllers.get(request.getRequestURI());
}
}
19 changes: 19 additions & 0 deletions src/main/java/core/mvc/view/JsonView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package core.mvc.view;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

public class JsonView implements View{
@Override
public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(mapper.writeValueAsString(model));
}

}
24 changes: 24 additions & 0 deletions src/main/java/core/mvc/view/JspView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package core.mvc.view;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class JspView implements View{
private String url;

public JspView(String url) {
this.url = url;
}

@Override
public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
for (Map.Entry<String, ?> entry : model.entrySet()) {
request.setAttribute(entry.getKey(), entry.getValue());
}

RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
}
18 changes: 18 additions & 0 deletions src/main/java/core/mvc/view/RedirectView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package core.mvc.view;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class RedirectView implements View {
private final String url;

public RedirectView(String url) {
this.url = url;
}

@Override
public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.sendRedirect(url);
}
}
9 changes: 9 additions & 0 deletions src/main/java/core/mvc/view/View.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package core.mvc.view;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public interface View {
void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
}
Loading