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주차 미션 / 서버 3조 정유혁 #30

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 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
a425bd6
Merge branch 'Konkuk-KUIT:main' into week4
You-Hyuk Apr 9, 2024
e4625f6
Feat: View 인터페이스 및 Jsp, Json 각각의 View 클래스 구현
YouHyuk Apr 10, 2024
4ebb441
Refactor: Controller 및 DispatcherServlet 에서 View를 반환하도록 변경
YouHyuk Apr 10, 2024
d35328a
Refactor: 각각의 Controller가 View를 반환하도록 변경
YouHyuk Apr 10, 2024
c1261a3
Feat: ModelAndView 클래스 추가 및 View, DispatcherServlet 수정
YouHyuk Apr 10, 2024
3069765
Refactor: JspView/JsonView model에 값 추가 (확인 필요)
YouHyuk Apr 10, 2024
f2e58b8
Feat: AbstractController
YouHyuk Apr 10, 2024
c9db6a9
Refactor: Controller들의 반환값을 ModelAndView로 변환 및 AbstractController 상속
YouHyuk Apr 10, 2024
4720908
Refactor: AbstractController 변경 및 Controller 수정
YouHyuk Apr 11, 2024
80965d0
Refactor: Controller 인터페이스 excute 수정 및 setSession 메서드 정의, DispatcherS…
YouHyuk Apr 11, 2024
d035591
Refactor: Redirect_PREFIX 수정 및 정리
YouHyuk Apr 11, 2024
f7d9e9d
Refactor: Controller excute 수정 및 Model 값을 담아 반환,
YouHyuk Apr 11, 2024
f2753dd
Refactor: 주석 및 코드 정리
YouHyuk Apr 11, 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
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.

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

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

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

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

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

public interface Controller {
static final String REDIRECT = "redirect:";
ModelAndView execute(Map<String, String> paraMap) throws IOException;

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

import core.view.View;

import javax.servlet.RequestDispatcher;
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;
import java.util.logging.Logger;

@WebServlet(name = "dispatcher", urlPatterns = "/", loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(DispatcherServlet.class.getName());


private RequestMapping requestMapping;
private static final String REDIRECT_PREFIX = "redirect:";

@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;
}
}
19 changes: 19 additions & 0 deletions src/main/java/core/mvc/ForwardController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package core.mvc;

import java.io.IOException;
import java.util.Map;

public class ForwardController extends AbstractController {
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> paraMap) throws IOException {
return jspView(forwardUrl);
}
}
25 changes: 25 additions & 0 deletions src/main/java/core/mvc/ModelAndView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package core.mvc;

import core.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 void addModel(String key, Object val){
model.put(key, val);
}

public void render(HttpServletRequest req, HttpServletResponse resp) throws Exception {
view.render(model, req, resp);
}
}
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());
}
}
24 changes: 24 additions & 0 deletions src/main/java/core/view/JsonView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package core.view;

import com.fasterxml.jackson.databind.ObjectMapper;

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

public class JsonView implements View{

@Override
public void render(Map<String, Object> model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
ObjectMapper mapper = new ObjectMapper();
resp.setContentType("application/json;charset=UTF-8");
PrintWriter out = resp.getWriter();
model.forEach((key, value) -> req.setAttribute(key, value));
out.print(mapper.writeValueAsString(req));
}

}
27 changes: 27 additions & 0 deletions src/main/java/core/view/JspView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package core.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 final String viewName;

private static final String REDIRECT_PREFIX = "redirect:";

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

@Override
public void render(Map<String, Object> model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
model.forEach((key, value) -> req.setAttribute(key, value));
if (viewName.startsWith(REDIRECT_PREFIX)){
resp.sendRedirect(viewName.substring(REDIRECT_PREFIX.length()));
return;
}
RequestDispatcher rd = req.getRequestDispatcher(viewName);
rd.forward(req, resp);
}
}
9 changes: 9 additions & 0 deletions src/main/java/core/view/View.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package core.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 req, HttpServletResponse resp) throws Exception;
}
Loading