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구현 / 3단계] 로이(김덕우) 미션 제출합니다. #631

Merged
merged 5 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
24 changes: 0 additions & 24 deletions app/src/main/java/com/techcourse/ManualHandlerAdapter.java

This file was deleted.

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

This file was deleted.

30 changes: 17 additions & 13 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,40 @@

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 login(final HttpServletRequest request, final HttpServletResponse response) {
if (UserSession.isLoggedIn(request.getSession())) {
return new ModelAndView(new JspView("redirect:/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 tryLogin(request, user);
})
.orElse("redirect:/401.jsp");
.orElse(new ModelAndView(new JspView("redirect:/401.jsp")));
}

private String login(final HttpServletRequest request, final User user) {
private ModelAndView tryLogin(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("redirect:/index.jsp"));
}
return "redirect:/401.jsp";
return new ModelAndView(new JspView("redirect:/401.jsp"));
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
package com.techcourse.controller;

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 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 LoginViewController implements Controller {
@Controller
public class LoginViewController {

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

@Override
public String execute(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
@RequestMapping(value = "/login/view", method = RequestMethod.GET)
public ModelAndView getLoginView(final HttpServletRequest req, final HttpServletResponse res) {
return UserSession.getUserFrom(req.getSession())
.map(user -> {
log.info("logged in {}", user.getAccount());
return "redirect:/index.jsp";
return new ModelAndView(new JspView("redirect:/index.jsp"));
})
.orElse("/login.jsp");
.orElse(new ModelAndView(new JspView("/login.jsp")));
}
}
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.GET)
public ModelAndView logout(final HttpServletRequest req, final HttpServletResponse res) {
final var session = req.getSession();
session.removeAttribute(UserSession.SESSION_KEY);
return "redirect:/";
return new ModelAndView(new JspView("redirect:/"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,25 @@

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 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 RegisterController implements Controller {
@Controller
public class RegisterController {

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

return "redirect:/index.jsp";
return new ModelAndView(new JspView("redirect:/index.jsp"));
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
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 RegisterViewController implements Controller {
@Controller
public class RegisterViewController {

@Override
public String execute(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
return "/register.jsp";
@RequestMapping(value = "/register/view", method = RequestMethod.GET)
public ModelAndView getRegisterView(final HttpServletRequest req, final HttpServletResponse res) {
return new ModelAndView(new JspView("/register.jsp"));
}
}
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 TEXT_PLAIN_UTF8_VALUE = "text/plain;charset=UTF-8";
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package com.techcourse;
package webmvc.org.springframework.web.servlet;

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.tobe.HandlerAdapter;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerAdapterRegistry;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerMapping;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerMappingRegistry;
import webmvc.org.springframework.web.servlet.view.JspView;

public class DispatcherServlet extends HttpServlet {

Expand Down Expand Up @@ -52,22 +50,12 @@ protected void service(final HttpServletRequest request, final HttpServletRespon

ModelAndView modelAndView = handlerAdapter.handle(request, response, handler);

JspView view = (JspView) modelAndView.getView();
move(view.getView(), request, response);
View view = modelAndView.getView();
view.render(modelAndView.getModel(), request, response);

} catch (Throwable e) {
log.error("Exception : {}", e.getMessage(), e);
throw new ServletException(e.getMessage());
}
}

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);
}
}

Choose a reason for hiding this comment

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

지금 Controller가 제대로 동작하고 있는지 http://localhost:8080/login/view와 같은 url로 확인했을 때, 제대로 된 페이지 뷰가 나오지 않는 걸 확인했어요!
오늘 강의 초반에도 언급되었던 DispatcherServletInitializer의 패키지 위치 때문인 것 같아요!

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

import jakarta.servlet.ServletContext;
import org.slf4j.Logger;
Expand All @@ -22,10 +22,8 @@ public void onStartup(final ServletContext servletContext) {
final var dispatcherServlet = new DispatcherServlet();

dispatcherServlet.addHandlerMapping(new AnnotationHandlerMapping("com.techcourse"));
dispatcherServlet.addHandlerMapping(new ManualHandlerMapping());

dispatcherServlet.addHandlerAdapter(new AnnotationHandlerAdapter());
dispatcherServlet.addHandlerAdapter(new ManualHandlerAdapter());

dispatcherServlet.init();

Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ public void addHandlerAdapter(HandlerAdapter handlerAdapter) {
}

public HandlerAdapter getHandlerAdapter(Object handler) {
for (HandlerAdapter handlerAdapter : this.handlerAdapters) {
if (handlerAdapter.isSupport(handler)) {
return handlerAdapter;
}
}
throw new IllegalArgumentException("해당 handler를 찾을 수 없습니다.");
return this.handlerAdapters.stream()
.filter(handlerAdapter -> handlerAdapter.isSupport(handler))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("해당 handler를 찾을 수 없습니다."));
Comment on lines +19 to +22

Choose a reason for hiding this comment

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

피드백 반영 좋아요 👍👍

}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
package webmvc.org.springframework.web.servlet.view;

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.util.Map;

public class JsonView implements View {

private static final ObjectMapper MAPPER = new ObjectMapper();
private static final int DEFAULT_RETURN_SIZE = 1;

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, HttpServletResponse response) throws Exception {
String jsonValue = MAPPER.writeValueAsString(model);

if (model.size() == DEFAULT_RETURN_SIZE) {
response.setContentType(MediaType.TEXT_PLAIN_UTF8_VALUE);
response.getWriter().write(jsonValue);
return;
}

response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.getWriter().write(jsonValue);
}
}
Loading
Loading