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

[MVC - Step 2] 효오 미션 제출합니다. #59

Merged
merged 32 commits into from
Oct 21, 2019
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
056f1d4
feat: JsonView 구현
hyojaekim Oct 8, 2019
cd14aa4
feat: 어노테이션 기반 회원가입, 조회, 수정하는 기능 추가
hyojaekim Oct 8, 2019
1c03b83
refactor: getBody 메서드 로직 변경
hyojaekim Oct 9, 2019
c8d7ccf
feat: 기존 컨트롤러 -> 어노테이션 기반 HomeController 추가
hyojaekim Oct 9, 2019
f7b1f0a
feat: 기존 컨트롤러 -> 어노테이션 기반 UserController 추가
hyojaekim Oct 9, 2019
1e7a8a5
refactor: 기존 레거시 컨트롤러 제거
hyojaekim Oct 9, 2019
ad3f4ef
feat: 기존 컨트롤러 로직 -> 어노테이션 기반으로 변경
hyojaekim Oct 9, 2019
27a3f62
test: CreateUserControllerTest 추가
hyojaekim Oct 9, 2019
aa7c258
test: LoginControllerTest 추가
hyojaekim Oct 9, 2019
e664f4e
feat: HandlerAdapter 추가
hyojaekim Oct 12, 2019
1cbc878
feat: HandlerAdapter 적용
hyojaekim Oct 12, 2019
fc5eaa3
refactor: (toJson 메소드) JsonView -> JsonUtils 이동
hyojaekim Oct 12, 2019
608af68
feat: CreateUserService 추가
hyojaekim Oct 13, 2019
e64d1fc
refactor: CreateUserService 리턴 타입 변경
hyojaekim Oct 13, 2019
8d7ba14
style: Controller, Service 클래스 이름 수정
hyojaekim Oct 13, 2019
d6a956a
test: UserCreateService 유저 생성 테스트 추가
hyojaekim Oct 13, 2019
54dc9f4
feat: LoginService, UserSearchService 추가
hyojaekim Oct 13, 2019
b53d113
test: LoginService 테스트 추가
hyojaekim Oct 13, 2019
0f22c61
fix: 로그인 세션 버그 수정
hyojaekim Oct 13, 2019
85582cb
feat: ArgumentResolver 적용
hyojaekim Oct 15, 2019
3cb42e8
test: ArgumentResolverTest 추가
hyojaekim Oct 15, 2019
5005591
refactor: HandlerExecutionHandlerAdapter 불필요한 로직 제거
hyojaekim Oct 18, 2019
73d9421
feat: ArgumentResolverAdapter 추가
hyojaekim Oct 19, 2019
d2b6c3b
feat: RequestResolverAdapter 구현
hyojaekim Oct 19, 2019
2584a09
feat: ResponseResolverAdapter 구현
hyojaekim Oct 19, 2019
8da33e7
feat: RequestParamResolverAdapter 구현
hyojaekim Oct 19, 2019
7f6243d
feat: ArgumnetResolverAdapter 적용
hyojaekim Oct 19, 2019
166180b
refactor: 메소드 분리 및 예외 추가
hyojaekim Oct 19, 2019
aaf07d1
test: ArgumentResolver 테스트 추가
hyojaekim Oct 19, 2019
2b4f779
style: ArgumentResolver 패키지 생성 및 이동
hyojaekim Oct 20, 2019
d13bdc3
refactor: UserCreateService addUser 리턴 타입 변경
hyojaekim Oct 20, 2019
623c867
fix: 실패하는 테스트 수정
hyojaekim Oct 20, 2019
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
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ private void renderByHandler(HttpServletRequest req, HttpServletResponse resp, H
try {
ModelAndView mav = handler.handle(req, resp);
View view = mav.getView();
view.render(mav.getModel(), req, resp);

if (view != null) {
view.render(mav.getModel(), req, resp);
}
} catch (Exception e) {
logger.debug(e.getMessage());
throw new ServletException();
Expand Down
31 changes: 31 additions & 0 deletions nextstep-mvc/src/main/java/nextstep/mvc/tobe/JsonView.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,43 @@
package nextstep.mvc.tobe;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import nextstep.web.support.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class JsonView implements View {
private static final Logger logger = LoggerFactory.getLogger(JsonView.class);

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

if (model.isEmpty()) {
return;
}

String json = toJson(model);
logger.debug("Json : {}", json);
response.getWriter().write(json);
}

private String toJson(Map<String, ?> model) throws JsonProcessingException {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JsonUtils라는 클래스가 있는데 해당 클래스로 옮겨보면 어떨까요 :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

놓친 부분이 있었네요! 피드백 감사합니다.

ObjectMapper mapper = new ObjectMapper();

if (model.size() == 1) {
Object value = model.values()
.stream()
.findFirst()
.orElseThrow(IllegalArgumentException::new);

return mapper.writeValueAsString(value);
}

return mapper.writeValueAsString(model);
}
}
8 changes: 0 additions & 8 deletions slipp/src/main/java/slipp/ManualHandlerMapping.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import nextstep.mvc.tobe.HandlerExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import slipp.controller.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -20,13 +19,6 @@ public class ManualHandlerMapping implements HandlerMapping {

@Override
public void initialize() {
mappings.put("/", new HomeController());
mappings.put("/users", new ListUserController());
mappings.put("/users/profile", new ProfileController());
mappings.put("/users/create", new CreateUserController());
mappings.put("/users/updateForm", new UpdateFormUserController());
mappings.put("/users/update", new UpdateUserController());

logger.info("Initialized Request Mapping!");
mappings.keySet().forEach(path -> {
logger.info("Path : {}, Controller : {}", path, mappings.get(path).getClass());
Expand Down
36 changes: 25 additions & 11 deletions slipp/src/main/java/slipp/controller/CreateUserController.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
package slipp.controller;

import slipp.domain.User;
import slipp.support.db.DataBase;
import nextstep.mvc.asis.Controller;
import nextstep.mvc.tobe.JspView;
import nextstep.mvc.tobe.ModelAndView;
import nextstep.mvc.tobe.RedirectView;
import nextstep.web.annotation.Controller;
import nextstep.web.annotation.RequestMapping;
import nextstep.web.annotation.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import slipp.domain.User;
import slipp.support.db.DataBase;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CreateUserController implements Controller {
private static final Logger log = LoggerFactory.getLogger(CreateUserController.class);
@Controller
public class CreateUserController {
private static final Logger logger = LoggerFactory.getLogger(CreateUserController.class);

@RequestMapping(value = "/users/form", method = RequestMethod.GET)
public ModelAndView signUpPage(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView(new JspView("/user/form.jsp"));
}

@RequestMapping(value = "/users/create", method = RequestMethod.POST)
public ModelAndView signUp(HttpServletRequest request, HttpServletResponse response) {
User user = new User(request.getParameter("userId"),
request.getParameter("password"),
request.getParameter("name"),
request.getParameter("email"));

@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
User user = new User(req.getParameter("userId"), req.getParameter("password"), req.getParameter("name"),
req.getParameter("email"));
log.debug("User : {}", user);
logger.debug("User : {}", user);

DataBase.addUser(user);
return "redirect:/";
return new ModelAndView(new RedirectView("/"));
}
}
21 changes: 15 additions & 6 deletions slipp/src/main/java/slipp/controller/HomeController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
package slipp.controller;

import nextstep.mvc.tobe.JspView;
import nextstep.mvc.tobe.ModelAndView;
import nextstep.web.annotation.Controller;
import nextstep.web.annotation.RequestMapping;
import nextstep.web.annotation.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import slipp.support.db.DataBase;
import nextstep.mvc.asis.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HomeController implements Controller {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
req.setAttribute("users", DataBase.findAll());
return "home.jsp";
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("users", DataBase.findAll());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

layer 를 분리해보면 어떨까요?
https://wckhg89.tistory.com/13 (layer 부분만 참고하셔서 보면 좋을 것 같아요!)

Copy link
Author

@hyojaekim hyojaekim Oct 15, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Service Layer 만드려고 생각은 했으나, MVC 프레임워크에 집중하려고 했습니다!
추가 미션으로 ArgumentResolver를 구현하고, Service Layer는 일부만 구현했습니다 :)

return new ModelAndView(new JspView("home.jsp"));
}
}
19 changes: 0 additions & 19 deletions slipp/src/main/java/slipp/controller/ListUserController.java

This file was deleted.

52 changes: 36 additions & 16 deletions slipp/src/main/java/slipp/controller/LoginController.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
package slipp.controller;

import nextstep.mvc.asis.Controller;
import nextstep.mvc.tobe.JspView;
import nextstep.mvc.tobe.ModelAndView;
import nextstep.mvc.tobe.RedirectView;
import nextstep.web.annotation.Controller;
import nextstep.web.annotation.RequestMapping;
import nextstep.web.annotation.RequestMethod;
import slipp.controller.UserSessionUtils;
import slipp.domain.User;
import slipp.support.db.DataBase;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginController implements Controller {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String userId = req.getParameter("userId");
String password = req.getParameter("password");
@Controller
public class LoginController {
private static final String USER_ID = "userId";
private static final String PASSWORD = "password";
private static final String LOGIN_FAILED = "loginFailed";

@RequestMapping(value = "/users/loginForm", method = RequestMethod.GET)
public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView(new JspView("/user/login.jsp"));
}

@RequestMapping(value = "/users/login", method = RequestMethod.POST)
public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
String userId = request.getParameter(USER_ID);
String password = request.getParameter(PASSWORD);
User user = DataBase.findUserById(userId);
if (user == null) {
req.setAttribute("loginFailed", true);
return "/user/login.jsp";
}
if (user.matchPassword(password)) {
HttpSession session = req.getSession();

if (user != null && user.matchPassword(password)) {
HttpSession session = request.getSession();
session.setAttribute(UserSessionUtils.USER_SESSION_KEY, user);
return "redirect:/";
} else {
req.setAttribute("loginFailed", true);
return "/user/login.jsp";
return new ModelAndView(new RedirectView("/"));
}

request.setAttribute(LOGIN_FAILED, true);
return new ModelAndView(new JspView("/user/login.jsp"));
}

@RequestMapping(value = "/users/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
session.removeAttribute(UserSessionUtils.USER_SESSION_KEY);
return new ModelAndView(new RedirectView("/"));
}
}
16 changes: 0 additions & 16 deletions slipp/src/main/java/slipp/controller/LogoutController.java

This file was deleted.

21 changes: 0 additions & 21 deletions slipp/src/main/java/slipp/controller/ProfileController.java

This file was deleted.

22 changes: 0 additions & 22 deletions slipp/src/main/java/slipp/controller/UpdateFormUserController.java

This file was deleted.

28 changes: 0 additions & 28 deletions slipp/src/main/java/slipp/controller/UpdateUserController.java

This file was deleted.

Loading