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단계] 준팍(박준현) 미션 제출합니다. #595

Merged
merged 9 commits into from
Sep 25, 2023
23 changes: 20 additions & 3 deletions app/src/main/java/com/techcourse/DispatcherServletInitializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.WebApplicationInitializer;
import webmvc.org.springframework.web.servlet.HandlerAdapterRegistry;
import webmvc.org.springframework.web.servlet.HandlerMappingRegistry;
import webmvc.org.springframework.web.servlet.mvc.DispatcherServlet;
import webmvc.org.springframework.web.servlet.mvc.tobe.AnnotationHandlerMapping;
import webmvc.org.springframework.web.servlet.mvc.tobe.HandlerExecutionHandlerAdapter;

/**
* Base class for {@link WebApplicationInitializer}
* implementations that register a {@link DispatcherServlet} in the servlet context.
* Base class for {@link WebApplicationInitializer} implementations that register a {@link DispatcherServlet} in the
* servlet context.
*/
public class DispatcherServletInitializer implements WebApplicationInitializer {

Expand All @@ -17,7 +22,7 @@ public class DispatcherServletInitializer implements WebApplicationInitializer {

@Override
public void onStartup(final ServletContext servletContext) {
final var dispatcherServlet = new DispatcherServlet();
final var dispatcherServlet = createDispatcherServlet();

final var registration = servletContext.addServlet(DEFAULT_SERVLET_NAME, dispatcherServlet);
if (registration == null) {
Expand All @@ -30,4 +35,16 @@ public void onStartup(final ServletContext servletContext) {

log.info("Start AppWebApplication Initializer");
}

private static DispatcherServlet createDispatcherServlet() {
AnnotationHandlerMapping annotationHandlerMapping = new AnnotationHandlerMapping("com.techcourse.controller");

Choose a reason for hiding this comment

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

컨트롤러를 검색할 패키지를 주입받아 완벽히 의존성을 끊어주었군요👍

HandlerMappingRegistry handlerMappingRegistry = new HandlerMappingRegistry(annotationHandlerMapping);
HandlerAdapterRegistry handlerAdapterRegistry = new HandlerAdapterRegistry(
new HandlerExecutionHandlerAdapter());

final var dispatcherServlet = new DispatcherServlet(handlerMappingRegistry, handlerAdapterRegistry);
dispatcherServlet.init();

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

This file was deleted.

19 changes: 19 additions & 0 deletions app/src/main/java/com/techcourse/controller/IndexController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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 IndexController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView(new JspView("/index.jsp"));
}
}
59 changes: 46 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,69 @@

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";
public static final String INDEX_JSP = "redirect:/index.jsp";
public static final String REDIRECT_401_JSP = "redirect:/401.jsp";

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLoginPage(HttpServletRequest req, HttpServletResponse res) {

String viewName = UserSession.getUserFrom(req.getSession())
.map(user -> {
log.info("logged in {}", user.getAccount());
return INDEX_JSP;
})
.orElse("/login.jsp");

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

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login(HttpServletRequest request, HttpServletResponse res) {
if (UserSession.isLoggedIn(request.getSession())) {
return new ModelAndView(new JspView(INDEX_JSP));
}

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

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

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest req, HttpServletResponse res) {

Choose a reason for hiding this comment

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

logout까지 LoginController로 이동하셨군요!!
이렇게 하면 프로젝트 규모가 켜졌을 때 로그아웃이 어디에 구현되어 있는지 헷갈릴 것 같아요. 저는 컨트롤러를 로그인과 로그아웃을 모두 포함하는 이름으로 추상화 하거나 로그아웃 컨트롤러로 다시 나누는게 좋아 보이는데 준팍은 혹시 왜 하나로 합쳤는지 설명해 주실 수 있나요?

Copy link
Member Author

Choose a reason for hiding this comment

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

제리의 의견에 공감합니다.
AuthController로 네이밍 변경하였습니다.

두 기능을 하나의 컨트롤러로 합친 이유는, 두 기능은 서로 다른 하나만 구현하였을 때
큰 의미가 없으니 한번에 관리를 해야한다고 생각했고,
그렇기 때문에 하나의 컨트롤러에서 관리해야겠다고 생각해서 입니다.

final var session = req.getSession();
session.removeAttribute(UserSession.SESSION_KEY);

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

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

}

This file was deleted.

15 changes: 0 additions & 15 deletions app/src/main/java/com/techcourse/controller/LogoutController.java

This file was deleted.

33 changes: 33 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,33 @@
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;
}

}
2 changes: 1 addition & 1 deletion app/src/main/webapp/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

<!-- before login -->
<div class="navbar-nav d-none d-md-inline-block ms-auto me-0 me-md-3 my-2 my-md-0">
<a class="nav-link" href="/login/view" role="button"><i class="fas fa-user fa-fw"></i>&nbsp;로그인</a>
<a class="nav-link" href="/login" role="button"><i class="fas fa-user fa-fw"></i>&nbsp;로그인</a>
</div>
<!-- before login -->

Expand Down
2 changes: 1 addition & 1 deletion app/src/main/webapp/index.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
</div>
<% } else { %>
<div class="navbar-nav d-none d-md-inline-block ms-auto me-0 me-md-3 my-2 my-md-0">
<a class="nav-link" href="/login/view" role="button"><i class="fas fa-user fa-fw"></i>&nbsp;로그인</a>
<a class="nav-link" href="/login" role="button"><i class="fas fa-user fa-fw"></i>&nbsp;로그인</a>
</div>
<% } %>
</nav>
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/webapp/register.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
</form>
</div>
<div class="card-footer text-center py-3">
<div class="small"><a href="/login/view">이미 가입하셨나요? 로그인 하러가기</a></div>
<div class="small"><a href="/login">이미 가입하셨나요? 로그인 하러가기</a></div>
</div>
</div>
</div>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package webmvc.org.springframework.web.servlet;

import java.util.Collections;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -23,11 +24,8 @@ public Object getObject(final String attributeName) {
return model.get(attributeName);
}

public Map<String, Object> getModel() {
return Collections.unmodifiableMap(model);
public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {
view.render(model, request, response);
}

public View getView() {
return view;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Map;

public interface View {

void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception;

String getPath();
}
Loading
Loading