Skip to content

Commit

Permalink
[MVC 구현하기 - 3단계] 레오(차영호) 미션 제출합니다. (#586)
Browse files Browse the repository at this point in the history
* feat: annotation 기반 핸들러 어댑터 작성

* feat: 핸들러 매핑 구현 및 DispatcherServlet 수정

* refactor: 메서드 추출

* feat: HandlerExecution 에서 instance 의존하도록 수정

* refactor: css 최신화

* refactor: 저장 타입 Object -> Controller 로 변경

* refactor: try-catch 예외 명시

* refactor: 사용하지 않는 클래스 제거

* refactor: 메서드 순서 변경

* feat: view render 로직 JspView 로 분리

* feat: UserContrller 추가

* feat: JsonView 구현

* feat: 레거시 컨트롤러 제거

* feat: 사용하지 않는 ManualHandler코드 제거

* refactor: 패키지 변경

* feat: PLAIN_TEXT 미디어 타입 추가

* feat: try-with-resources 적용
  • Loading branch information
youngh0 authored Sep 26, 2023
1 parent 88af1aa commit d205c7c
Show file tree
Hide file tree
Showing 14 changed files with 129 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.WebApplicationInitializer;
import webmvc.org.springframework.web.servlet.mvc.tobe.DispatcherServlet;

/**
* Base class for {@link WebApplicationInitializer}
Expand Down
22 changes: 0 additions & 22 deletions app/src/main/java/com/techcourse/ManualHandlerAdapter.java

This file was deleted.

40 changes: 0 additions & 40 deletions app/src/main/java/com/techcourse/ManualHandlerMapping.java

This file was deleted.

18 changes: 18 additions & 0 deletions app/src/main/java/com/techcourse/controller/ForwardController.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 ForwardController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView execute(final HttpServletRequest request, final HttpServletResponse response) {
return new ModelAndView(new JspView("/index.jsp"));
}
}
29 changes: 23 additions & 6 deletions app/src/main/java/com/techcourse/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,45 @@

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 {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
if (UserSession.isLoggedIn(req.getSession())) {
return "redirect:/index.jsp";
return new ModelAndView(new JspView("redirect:/index.jsp"));
}

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

return new ModelAndView(new JspView(viewName));
}

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

private String login(final HttpServletRequest request, final User user) {
Expand Down

This file was deleted.

15 changes: 10 additions & 5 deletions app/src/main/java/com/techcourse/controller/LogoutController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
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 {
@RequestMapping(value = "logout", method = RequestMethod.POST)
public ModelAndView logout(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
final var session = req.getSession();
session.removeAttribute(UserSession.SESSION_KEY);
return "redirect:/";
return new ModelAndView(new JspView("redirect:/"));
}
}
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
Expand Up @@ -2,4 +2,5 @@

public class MediaType {
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
public static final String PLAIN_TEXT_UTF8_VALUE = "text/plain;charset=UTF-8";
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.techcourse;
package webmvc.org.springframework.web.servlet.mvc.tobe;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
Expand All @@ -7,14 +7,11 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.mvc.tobe.AnnotationHandlerAdapter;
import webmvc.org.springframework.web.servlet.mvc.tobe.AnnotationHandlerMapping;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerAdapter;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerMapping;
import webmvc.org.springframework.web.servlet.view.JspView;
import webmvc.org.springframework.web.servlet.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DispatcherServlet extends HttpServlet {

Expand All @@ -35,9 +32,6 @@ public void init() {

private void initHandlerMappings() {
this.handlerMappings = new ArrayList<>();
ManualHandlerMapping manualHandlerMapping = new ManualHandlerMapping();
manualHandlerMapping.initialize();
handlerMappings.add(manualHandlerMapping);

AnnotationHandlerMapping annotationHandlerMapping = new AnnotationHandlerMapping();
annotationHandlerMapping.initialize();
Expand All @@ -46,7 +40,6 @@ private void initHandlerMappings() {

private void initHandlerAdapters() {
this.handlerAdapters = new ArrayList<>();
handlerAdapters.add(new ManualHandlerAdapter());
handlerAdapters.add(new AnnotationHandlerAdapter());
}

Expand All @@ -59,7 +52,9 @@ protected void service(final HttpServletRequest request, final HttpServletRespon
HandlerAdapter handlerAdapter = findHandlerAdapter(handler);

ModelAndView modelAndView = handlerAdapter.handle(request, response, handler);
move(modelAndView.getViewName(), request, response);
View view = modelAndView.getView();
Map<String, Object> model = modelAndView.getModel();
view.render(model, request, response);
} catch (Throwable e) {
log.error("Exception : {}", e.getMessage(), e);
throw new ServletException(e.getMessage());
Expand All @@ -80,14 +75,4 @@ private HandlerAdapter findHandlerAdapter(Object handler) {
.findAny()
.orElseThrow(() -> new IllegalArgumentException("요청을 처리할 수 있는 핸들러 어댑터가 없습니다."));
}

private void move(final String viewName, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
if (viewName.startsWith(JspView.REDIRECT_PREFIX)) {
response.sendRedirect(viewName.substring(JspView.REDIRECT_PREFIX.length()));
return;
}

final var requestDispatcher = request.getRequestDispatcher(viewName);
requestDispatcher.forward(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
package webmvc.org.springframework.web.servlet.view;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import web.org.springframework.http.MediaType;
import webmvc.org.springframework.web.servlet.View;

import java.io.PrintWriter;
import java.util.Map;

public class JsonView implements View {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
try (PrintWriter writer = response.getWriter()) {
writeBody(model, response, writer);
}

}

private void writeBody(Map<String, ?> model, HttpServletResponse response, PrintWriter writer) throws JsonProcessingException {
if (model.size() == 1) {
response.setContentType(MediaType.PLAIN_TEXT_UTF8_VALUE);
writeBodyByPlainText(model, writer);
} else {
String value = objectMapper.writeValueAsString(model);
writer.write(value);
}
}

private void writeBodyByPlainText(Map<String, ?> model, PrintWriter writer) {
for (Map.Entry<String, ?> entry : model.entrySet()) {
writer.write(entry.getValue().toString());
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,23 @@ public JspView(final String viewName) {

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// todo
if (viewName.startsWith(JspView.REDIRECT_PREFIX)) {
response.sendRedirect(viewName.substring(JspView.REDIRECT_PREFIX.length()));
return;
}

model.keySet().forEach(key -> {
log.debug("attribute name : {}, value : {}", key, model.get(key));
request.setAttribute(key, model.get(key));
});

// todo
final var requestDispatcher = request.getRequestDispatcher(viewName);
requestDispatcher.forward(request, response);
}

@Override
public String getName() {
return viewName;
}

@Override
Expand Down

0 comments on commit d205c7c

Please sign in to comment.