Skip to content

Commit

Permalink
[MVC 구현하기 - 3단계] 제이미(임정수) 미션 제출합니다. (#593)
Browse files Browse the repository at this point in the history
* fix: 충돌 문제 해결

* refactor: 코드 컨벤션 관련 수정

* fix: basePackage가 여러개여도 처리가 가능하도록 수정

* refactor: render를 ModelAndView 내부에서 수행하도록 수정

* feat: UserController 추가

- 요구 사항을 위해 추가

* feat: JsonView 반환 기능 추가

* refactor: 모든 컨트롤러를 너오테이션 기반 mvc로 변경

* refactor: 레거시 코드 제거

* rename: DispatcherServlet 패키지 이동

* feat: 에외 처리 추가

* fix: 충돌 문제 해결
  • Loading branch information
JJ503 authored Sep 25, 2023
1 parent 7347ffc commit 42f1a06
Show file tree
Hide file tree
Showing 18 changed files with 153 additions and 157 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.WebApplicationInitializer;
import webmvc.org.springframework.web.servlet.mvc.DispatcherServlet;
import webmvc.org.springframework.web.servlet.mvc.HandlerAdapterRegistry;
import webmvc.org.springframework.web.servlet.mvc.HandlerMappingRegistry;
import webmvc.org.springframework.web.servlet.mvc.asis.ControllerHandlerAdapter;
import webmvc.org.springframework.web.servlet.mvc.tobe.AnnotationHandlerMapping;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerExecutionHandlerAdapter;

Expand Down Expand Up @@ -42,15 +42,13 @@ public void onStartup(final ServletContext servletContext) {
private static HandlerMappingRegistry initializedHandlerAdapater() {
final HandlerMappingRegistry handlerMappingRegistry = new HandlerMappingRegistry();
handlerMappingRegistry.addHandlerMapping(new AnnotationHandlerMapping("com.techcourse.controller"));
handlerMappingRegistry.addHandlerMapping(new ManualHandlerMapping());

return handlerMappingRegistry;
}

private static HandlerAdapterRegistry initializedHandlerAdapterRegistry() {
final HandlerAdapterRegistry handlerAdapterRegistry = new HandlerAdapterRegistry();
handlerAdapterRegistry.addHandlerAdapter(new HandlerExecutionHandlerAdapter());
handlerAdapterRegistry.addHandlerAdapter(new ControllerHandlerAdapter());

return handlerAdapterRegistry;
}
Expand Down
41 changes: 0 additions & 41 deletions app/src/main/java/com/techcourse/ManualHandlerMapping.java

This file was deleted.

39 changes: 27 additions & 12 deletions app/src/main/java/com/techcourse/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,51 @@

import com.techcourse.domain.User;
import com.techcourse.repository.InMemoryUserRepository;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.mvc.asis.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.view.JspView;

public class LoginController implements Controller {
@Controller
public class LoginController {

private static final Logger log = LoggerFactory.getLogger(LoginController.class);

@Override
public String execute(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
if (UserSession.isLoggedIn(req.getSession())) {
return "redirect:/index.jsp";
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView execute(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
if (UserSession.isLoggedIn(request.getSession())) {
return new ModelAndView(new JspView("/index.jsp"));
}

return InMemoryUserRepository.findByAccount(req.getParameter("account"))
return InMemoryUserRepository.findByAccount(request.getParameter("account"))
.map(user -> {
log.info("User : {}", user);
return login(req, user);
return login(request, user);
})
.orElse("redirect:/401.jsp");
.orElse(new ModelAndView(new JspView("/401.jsp")));
}

private String login(final HttpServletRequest request, final User user) {
private ModelAndView login(final HttpServletRequest request, final User user) {
if (user.checkPassword(request.getParameter("password"))) {
final var session = request.getSession();
session.setAttribute(UserSession.SESSION_KEY, user);
return "redirect:/index.jsp";
return new ModelAndView(new JspView("/index.jsp"));
}
return "redirect:/401.jsp";
return new ModelAndView(new JspView("/401.jsp"));
}

@RequestMapping(value = "/login/view", method = RequestMethod.GET)
public ModelAndView show(final HttpServletRequest request, final HttpServletResponse response) {
return UserSession.getUserFrom(request.getSession())
.map(user -> {
log.info("logged in {}", user.getAccount());
return new ModelAndView(new JspView("redirect:/index.jsp"));
})
.orElse(new ModelAndView(new JspView("/login.jsp")));
}
}

This file was deleted.

18 changes: 12 additions & 6 deletions app/src/main/java/com/techcourse/controller/LogoutController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package com.techcourse.controller;

import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.mvc.asis.Controller;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.view.JspView;

public class LogoutController implements Controller {
@Controller
public class LogoutController {

@Override
public String execute(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
final var session = req.getSession();
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(final HttpServletRequest request, final HttpServletResponse response) {
final var session = request.getSession();
session.removeAttribute(UserSession.SESSION_KEY);
return "redirect:/";

return new ModelAndView(new JspView("redirect:/"));
}
}
18 changes: 18 additions & 0 deletions app/src/main/java/com/techcourse/controller/MainController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.techcourse.controller;

import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.view.JspView;

@Controller
public class MainController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView show(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
return new ModelAndView(new JspView("/index.jsp"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@
public class RegisterController {

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView register(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
public ModelAndView register(final HttpServletRequest request, final HttpServletResponse response) {
final var user = new User(2,
req.getParameter("account"),
req.getParameter("password"),
req.getParameter("email"));
request.getParameter("account"),
request.getParameter("password"),
request.getParameter("email"));
InMemoryUserRepository.save(user);

return new ModelAndView(new JspView("/index.jsp"));
return new ModelAndView(new JspView("redirect:/index.jsp"));
}

@RequestMapping(value = "/register/view", method = RequestMethod.GET)
public ModelAndView showRegister(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
public ModelAndView show(final HttpServletRequest request, final HttpServletResponse response) {
return new ModelAndView(new JspView("/register.jsp"));
}
}
32 changes: 32 additions & 0 deletions app/src/main/java/com/techcourse/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.techcourse.controller;

import com.techcourse.domain.User;
import com.techcourse.repository.InMemoryUserRepository;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.view.JsonView;

@Controller
public class UserController {

private static final Logger log = LoggerFactory.getLogger(UserController.class);

@RequestMapping(value = "/api/user", method = RequestMethod.GET)
public ModelAndView show(HttpServletRequest request, HttpServletResponse response) {
final String account = request.getParameter("account");
log.debug("user id : {}", account);

final ModelAndView modelAndView = new ModelAndView(new JsonView());
final User user = InMemoryUserRepository.findByAccount(account)
.orElseThrow();

modelAndView.addObject("user", user);
return modelAndView;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package webmvc.org.springframework.web.servlet;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.exception.RenderingException;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -19,6 +23,14 @@ public ModelAndView addObject(final String attributeName, final Object attribute
return this;
}

public void render(final HttpServletRequest request, HttpServletResponse response) {
try {
view.render(model, request, response);
} catch (Exception e) {
throw new RenderingException("렌더링 중 문제가 발생했습니다.");
}
}

public Object getObject(final String attributeName) {
return model.get(attributeName);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package webmvc.org.springframework.web.servlet.exception;

public class RenderingException extends IllegalArgumentException {

public RenderingException(final String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.techcourse;
package webmvc.org.springframework.web.servlet.mvc;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.mvc.HandlerAdapter;
import webmvc.org.springframework.web.servlet.mvc.HandlerAdapterRegistry;
import webmvc.org.springframework.web.servlet.mvc.HandlerMappingRegistry;
import webmvc.org.springframework.web.servlet.view.JspView;

public class DispatcherServlet extends HttpServlet {

Expand All @@ -30,18 +27,27 @@ public void init() {
}

@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
protected void service(final HttpServletRequest request, final HttpServletResponse response) {
final String requestURI = request.getRequestURI();
log.debug("Method : {}, Request URI : {}", request.getMethod(), requestURI);

try {
final Object handle = handlerMappingRegistry.getHandler(request);
final HandlerAdapter handlerAdapter = handlerAdapterRegistry.getHandlerAdapter(handle);
final ModelAndView modelAndView = handlerAdapter.handle(handle, request, response);
modelAndView.getView().render(modelAndView.getModel(), request, response);
final var handle = handlerMappingRegistry.getHandler(request);
final var handlerAdapter = handlerAdapterRegistry.getHandlerAdapter(handle);
final var modelAndView = handlerAdapter.handle(handle, request, response);
modelAndView.render(request, response);
} catch (IllegalArgumentException e) {
log.error("Exception : {}", e.getMessage(), e);

final var modelAndView = new ModelAndView(new JspView("/404.jsp"));
response.setStatus(404);
modelAndView.render(request, response);
} catch (Throwable e) {
log.error("Exception : {}", e.getMessage(), e);
throw new ServletException(e.getMessage());

final var modelAndView = new ModelAndView(new JspView("/500.jsp"));
response.setStatus(500);
modelAndView.render(request, response);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

public class HandlerAdapterRegistry {

final private List<HandlerAdapter> handlerAdapters = new ArrayList<>();
private final List<HandlerAdapter> handlerAdapters = new ArrayList<>();

public void addHandlerAdapter(final HandlerAdapter handlerAdapter) {
handlerAdapters.add(handlerAdapter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

public class HandlerMappingRegistry {

final private List<HandlerMapping> handlerMappings = new ArrayList<>();
private final List<HandlerMapping> handlerMappings = new ArrayList<>();

public void initialize() {
handlerMappings.forEach(HandlerMapping::initialize);
Expand Down

This file was deleted.

This file was deleted.

Loading

0 comments on commit 42f1a06

Please sign in to comment.