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

[톰캣 구현하기 - 1, 2단계] 다즐(최우창) 미션 제출합니다. #316

Merged
merged 13 commits into from
Sep 5, 2023

Conversation

woo-chang
Copy link
Member

안녕하세요 에코 :) 다즐입니다 🙇🏻‍♂️ 1, 2단계 리뷰 요청드립니다 ㅎㅎ

전체적인 흐름은 아래의 사진을 참고해주시면 될 것 같아요!

스크린샷 2023-09-04 오후 1 11 53

각각의 역할에 맞게 패키지를 아래와 같이 구성해 보았습니다.

  • common : 요청과 응답에 공통으로 사용되는 클래스
  • exception : 요청과 응답 상황에서 발생하는 커스텀 예외 클래스
  • handle : 요청을 처리하기 위한 핸들러와 이를 관리하는 핸들러 매핑 클래스
  • request : 요청 전반적으로 사용되는 클래스
  • response : 응답 전반적으로 사용되는 클래스

리뷰 잘 부탁드립니다 😎

@woo-chang woo-chang self-assigned this Sep 4, 2023
@woo-chang woo-chang changed the title [톰캣 구현하기 1,2단계] 다즐(최우창) 미션 제출합니다. [톰캣 구현하기 1, 2단계] 다즐(최우창) 미션 제출합니다. Sep 4, 2023
@woo-chang woo-chang changed the title [톰캣 구현하기 1, 2단계] 다즐(최우창) 미션 제출합니다. [톰캣 구현하기 - 1, 2단계] 다즐(최우창) 미션 제출합니다. Sep 4, 2023
@echo724
Copy link

echo724 commented Sep 4, 2023

이제 미션을 제출해서 오늘 저녁 - 밤 사이까지 리뷰 해드릴게요~!

Copy link

@echo724 echo724 left a comment

Choose a reason for hiding this comment

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

우테코 고수 다즐 코드 맛있게 잘 먹은것 같습니다.. 자바의 다양한 요소들을 잘 사용하시는 것 보고 역시나 다즐.. 싶었습니다. 구조도 깔끔하고 눈에 잘 보여서 좋았어요! 테스트 코드도 맛있었구요.. 고생 많았습니다..! 큰 구조 변화는 없고 궁금한 것들이랑 문제되는 부분만 커멘트 남겼어요! 다음 미션도 화이팅입니다!


public RegisterMappingInfo() {
super("/register");
try {
Copy link

Choose a reason for hiding this comment

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

ㅜㅜ 아름답네요. 리플렉션을 활용해서 각 핸들러의 메서드를 MappingInfo의 맵에 추가시킨거죠? 아름답읍니다..

Copy link
Member Author

@woo-chang woo-chang Sep 5, 2023

Choose a reason for hiding this comment

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

맞습니다 🤓 스프링 프레임워크와 비슷하게 구현하려다보니 해당 구조로 설계하고 구현하였습니다! 우선 사용만 한 느낌이라 제대로 사용하고 있는건지는 애매한 것 같아요 :(

private String getBody(final HttpRequest httpRequest) throws IOException {
final String uriPath = httpRequest.getUriPath();
final URL resource = ClassLoader.getSystemClassLoader().getResource(STATIC_DIRECTORY + uriPath);
final File file = new File(resource.getFile());
Copy link

Choose a reason for hiding this comment

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

이 부분에서 접근할 수 없는 파일로 요청한 경우 널포인트 예외가 발생하더라구요! 예를 들어 a.html이렇게 요청할 경우에는 NullPointException이 뜨는데 404로 리다이렉션 해주거나 무시하거나하는 처리는 어떨까요?

Copy link
Member Author

@woo-chang woo-chang Sep 5, 2023

Choose a reason for hiding this comment

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

좋은 방법인 것 같아요 🙇🏻‍♂️

페이지 처리 역할을 수행하는 ViewResolver를 구현하여 없는 페이지에 대한 예외 처리를 하도록 수정하였습니다 ㅎㅎ

import org.junit.jupiter.api.Test;

@SuppressWarnings("NonAsciiCharacters")
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
Copy link

Choose a reason for hiding this comment

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

오 이런 것도 있었군요.. 다즐이랑 페어프로그래밍 해봤으면 했었는데,, 자바의 다양한 요소들을 적재적소에 잘 사용하시는 것 같아요!

Copy link
Member Author

Choose a reason for hiding this comment

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

저도 에코랑 페어프로그래밍 하는 날 기대하고 있습니다 :)


@SuppressWarnings("NonAsciiCharacters")
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class ContentTypeTest {
Copy link

Choose a reason for hiding this comment

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

이 압도적 테스트들... 대단하시네요 다즐.. 이 많은걸 어떻게 다 하신거죠..?

Copy link
Member Author

Choose a reason for hiding this comment

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

잠을 포기했던 것 같습니다 ㅋㅋ ㅎㅎ..

Copy link

Choose a reason for hiding this comment

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

헉,, 잠을 포기하면서까지.. 멋있습니다..

final HttpRequest httpRequest = HttpRequest.parse(bufferedReader);
final HttpResponse httpResponse = new HttpResponse(httpRequest.getHttpVersion());
final HandlerMethod handlerMethod = HandlerMapping.getHandlerMethod(httpRequest);
handlerMethod.invokeMethod(httpRequest, httpResponse);
Copy link

Choose a reason for hiding this comment

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

이 부분은 궁금해서 질문 드립니다. 생성한 HttpResponse invokeMethod()를 타고 들어가보면 handler 메서드들(doPost,doGet)의 renderPage에서부터 response의 setter들이 사용되고 마지막에 outputStream.write를 할때 HttpResponse가 사용되는걸로 보입니다. 문제가 있거나 그런게 아니라 왜 상위 메서드에서 응답 객체를 만들어서 setter로 값을 설정하셨는지 궁금합니다! 그냥 renderPage에서 HttpResponse를 생성하고 반환만 하는식으로 해서 process 메서드까지 전파해도 되지 않을까요?

Copy link
Member Author

Choose a reason for hiding this comment

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

말씀해주신대로 handler에서 HttpResponse를 만들어 반환하는 방법도 좋은 방법이라고 생각합니다 :)

저는 이번 미션을 진행하면서 TomcatSpring Framework 코드를 직접 확인하고 비슷하게 구현해보고자 하는 것이 목표였습니다. 학습해야할 내용이기도 하고 이전까지 직접 코드를 까보면서 학습했던 경험이 없었거든요. 그래서 Spring Framework의 방식을 차용하고자 했던 것 같습니다.

스프링 프레임워크에서는 요청이 들어온 시점에서 HttpServletResponse가 만들어져있어 해당 객체를 통해 응답값을 설정할 수 있습니다. 컨트롤러의 메서드 매개변수로도 HttpServletResponse로 받아 조작할 수 있습니다.

깊게 알아보지는 않았지만, 불변으로 구현하지 않고 요청이 들어온 시점부터 응답을 조작할 수 있게 구현한 이유는 동적 애플리케이션을 위한 설계라고 합니다. 웹 서버는 동적으로 요청을 처리하기에 응답 객체는 런타임 중 여러가지 상태나 헤더, 쿠키, 바디 등을 변경할 수 있어야 합니다. 추가로 불변으로 만들어 상태를 수정할 때마다 새로운 객체를 생성해야한다면 메모리 사용량을 증가시키고, 가비지 컬렉션의 사용량이 증가합니다. 웹 서버에서는 이런 비효율성 또한 문제가 될 수 있다고 합니다.

위의 이유로 인해 응답 객체의 상태를 유연하게 변경할 수 있게 구현하였습니다. 🤓

Copy link

Choose a reason for hiding this comment

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

오오.. 깊이 있는 이유와 설명 감사합니다.. 웹 서버라는 특성이 설계에 영향을 줄 수 있겠네요! 배워갑니다 ㅎㅎ 고마워요 다즐~

Comment on lines 46 to 51
final List<String> lines = new ArrayList<>();
String line;
while ((line = bufferedReader.readLine()) != null && !"".equals(line)) {
lines.add(line);
}
return HttpRequestHeaders.parse(lines);
Copy link

Choose a reason for hiding this comment

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

final List<String> lines = bufferedReader
                    .lines()
                    .takeWhile(line -> !line.isEmpty())
                    .collect(Collectors.toList());

저는 bufferedReader의 lines()와 takeWhile 메서드를 사용했는데 이건 어떨까요?

Copy link
Member Author

Choose a reason for hiding this comment

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

가독성도 좋아지고 훨씬 깔끔한 방법인 것 같아요 👍👍 역시 에코 배워갑니다 :)

@sonarcloud
Copy link

sonarcloud bot commented Sep 5, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 9 Code Smells

0.0% 0.0% Coverage
0.0% 0.0% Duplication

warning The version of Java (11.0.20.1) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
Read more here

import org.apache.coyote.common.HttpStatus;
import org.apache.coyote.response.HttpResponse;

public class ViewResolver {
Copy link

Choose a reason for hiding this comment

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

와우 이렇게 빠르게 ViewResolver를 도입해 해결하다니.. 멋집니다~! 보면 코드 수정도 많고 구조 변화도 있었던 것 같은데,, 고생했어요 ~!!

@echo724 echo724 merged commit 22a9cc3 into woowacourse:woo-chang Sep 5, 2023
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants