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단계] 블랙캣(송우석) 미션 제출합니다. #591

Merged
merged 13 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from 10 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
5 changes: 2 additions & 3 deletions app/src/main/java/com/techcourse/Application.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package com.techcourse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Application {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,9 @@ public class DispatcherServletInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) {
final HandlerMappings handlerMappings = new HandlerMappings(List.of(
new ManualHandlerMapping(),
new AnnotationHandlerMapping("com.techcourse.controller")
));
final HandlerAdapters handlerAdapters = new HandlerAdapters(List.of(
new ManualHandlerAdapter(),
new AnnotationHandlerAdapter()
));
final var dispatcherServlet = new DispatcherServlet(handlerMappings, handlerAdapters);
Expand Down
26 changes: 0 additions & 26 deletions app/src/main/java/com/techcourse/ManualHandlerAdapter.java

This file was deleted.

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

This file was deleted.

3 changes: 1 addition & 2 deletions app/src/main/java/com/techcourse/TomcatStarter.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.techcourse;

import java.io.File;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.scan.StandardJarScanner;

import java.io.File;

public class TomcatStarter {

public static final String WEBAPP_DIR_LOCATION = "app/src/main/webapp/";
Expand Down
16 changes: 16 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,16 @@
package com.techcourse.controller;

import context.org.springframework.stereotype.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;

@Controller
public class IndexController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
return new ModelAndView(new JspView("/index.jsp"));
}
}
37 changes: 23 additions & 14 deletions app/src/main/java/com/techcourse/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,42 @@

import com.techcourse.domain.User;
import com.techcourse.repository.InMemoryUserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.mvc.asis.Controller;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpSession;
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 web.org.springframework.web.bind.annotation.RequestParam;
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 HttpSession session,
@RequestParam(value = "account") final String account,
@RequestParam("password") final String password
) {
if (UserSession.isLoggedIn(session)) {
return new ModelAndView(new JspView("redirect:/index.jsp"));
}

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

private String login(final HttpServletRequest request, final User user) {
if (user.checkPassword(request.getParameter("password"))) {
final var session = request.getSession();
private String login(final User user, final String password, final HttpSession session) {
if (user.checkPassword(password)) {
session.setAttribute(UserSession.SESSION_KEY, user);
return "redirect:/index.jsp";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
package com.techcourse.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpSession;
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 {
return UserSession.getUserFrom(req.getSession())
@RequestMapping(value = "/login/view", method = RequestMethod.GET)
public ModelAndView loginView(final HttpSession session) {
return UserSession.getUserFrom(session)
.map(user -> {
log.info("logged in {}", user.getAccount());
return "redirect:/index.jsp";
})
.orElse("/login.jsp");
.map(it -> new ModelAndView(new JspView(it)))
.orElse(new ModelAndView(new JspView("/login.jsp")));
}
}
19 changes: 11 additions & 8 deletions app/src/main/java/com/techcourse/controller/LogoutController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package com.techcourse.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.mvc.asis.Controller;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpSession;
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 HttpSession session) {
session.removeAttribute(UserSession.SESSION_KEY);
return "redirect:/";
return new ModelAndView(new JspView("redirect:/"));
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.techcourse.controller;

import com.techcourse.domain.User;
import com.techcourse.dto.RegisterRequest;
import com.techcourse.repository.InMemoryUserRepository;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import web.org.springframework.web.bind.annotation.RequestBody;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
Expand All @@ -14,18 +14,18 @@
public class RegisterController {

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView save(HttpServletRequest req, HttpServletResponse res) {
public ModelAndView save(@RequestBody final RegisterRequest registerRequest) {
final var user = new User(2,
req.getParameter("account"),
req.getParameter("password"),
req.getParameter("email"));
registerRequest.getAccount(),
registerRequest.getPassword(),
registerRequest.getEmail());
InMemoryUserRepository.save(user);

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

@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView show(HttpServletRequest req, HttpServletResponse res) {
@RequestMapping(value = "/register/view", method = RequestMethod.GET)
public ModelAndView show() {
return new ModelAndView(new JspView("/register.jsp"));
}
Comment on lines 16 to 30
Copy link

Choose a reason for hiding this comment

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

LoginController는 view에 대한 클래스가 분리되어있는 것으로 확인이 됩니다.
사소하지만 둘 중 하나로 통일성있게 변경해보는 것은 어떨까요?

Copy link
Author

Choose a reason for hiding this comment

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

미쳐 확인하지 못했네요!
회원가입 컨트롤러와 같이 하나의 컨트롤러로 통합하였습니다!

}
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.dto.UserRequest;
import com.techcourse.repository.InMemoryUserRepository;
import context.org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.bind.annotation.RequestBody;
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(@RequestBody final UserRequest request) {
final String account = request.getAccount();
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;
}
}
4 changes: 2 additions & 2 deletions app/src/main/java/com/techcourse/controller/UserSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.techcourse.domain.User;
import jakarta.servlet.http.HttpSession;

import java.util.Optional;

public class UserSession {
Expand All @@ -18,5 +17,6 @@ public static boolean isLoggedIn(final HttpSession session) {
return getUserFrom(session).isPresent();
}

private UserSession() {}
private UserSession() {
}
}
12 changes: 12 additions & 0 deletions app/src/main/java/com/techcourse/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,22 @@ public boolean checkPassword(String password) {
return this.password.equals(password);
}

public long getId() {
return id;
}

public String getAccount() {
return account;
}

public String getPassword() {
return password;
}

public String getEmail() {
return email;
}

@Override
public String toString() {
return "User{" +
Expand Down
29 changes: 29 additions & 0 deletions app/src/main/java/com/techcourse/dto/RegisterRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.techcourse.dto;

public class RegisterRequest {

private String account;
private String password;
private String email;

public RegisterRequest() {
Copy link

Choose a reason for hiding this comment

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

dto패키지 내부에 있는 클래스들에 대해서는 public생성자를 명시해주셨네요.
이유가 궁금합니다!

Copy link
Author

Choose a reason for hiding this comment

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

ObjectMapper 는 json 을 역직렬화 할 때 기본 생성자가 없다면 InvalidDefinitionException 예외가 터지게됩니다.
이는 Reflection API 가 클래스를 인스턴스화 할 때 기본생성자를 사용하기 때문입니다.
(@Entity 가 붙은 도메인 객체에서 기본 생성자를 넣어주는 이유와 같습니다.)

참고로 스프링에서는 기본적으로 추가적으로 jackson-module-parameter-names 모듈을 통해서 기본 생성자가 없는 경우 다른 방법(매개변수가 있는 생성자 등) 을 찾아서 역직렬화를 해준다고합니다!

}

public RegisterRequest(final String account, final String password, final String email) {
this.account = account;
this.password = password;
this.email = email;
}

public String getAccount() {
return account;
}

public String getPassword() {
return password;
}

public String getEmail() {
return email;
}
}
Loading
Loading