😀
fistkim TECH BLOG
  • Intro
  • 강의
    • Reactive Programming in Modern Java using Project Reactor
      • Reactor execution model 1
      • Reactor execution model 2
      • Reactor execution model 3 - parallelism
      • Reactor execution model 4 - overview
      • Transform
      • Combine
      • Side Effect Methods
      • Exception/Error handling
      • retry, retryWhen, repeat
      • BackPressure
      • Cold & Hot Streams
    • NEXTSTEP 클린코드 with java 9기
      • 정리노트
    • NEXTSTEP DDD 세레나데 2기
      • CH01 도메인 주도 설계 이해
      • CH02 크게 소리 내어 모델링 하기
      • CH03 도메인 주도 설계 기본 요소
      • CH04 도메인 주도 설계 아키텍처
      • CH05 도메인 이벤트
    • NEXTSTEP 인프라 공방 1기
      • 망 분리하기
      • 통신 확인하기
      • 도커 컨테이너 이해하기
      • [미션 1] 서비스 구성하기 실습
      • [미션 2] 서비스 배포하기 실습
      • 서버 진단하기
      • 어플리케이션 진단하기
      • [미션 3] 서비스 운영하기
      • 웹 성능 진단하기
      • 부하 테스트
      • k6
      • [미션 4] 성능 테스트
      • 리버스 프록시 개선하기
      • 캐싱 활용하기
      • [미션 5] 화면 응답 개선하기
      • Redis Annotation 및 설정
      • 인덱스 이해하기 & DB 튜닝
      • [미션 6-1] 조회 성능 개선하기
      • [미션 6-2] DB 이중화 적용
    • NEXTSTEP 만들면서 배우는 Spring 3기
      • CH01 올바른 방향 바라보기
      • CH02 HTTP 이해 - 웹 서버 구현
        • HTTP 파싱
        • HTTP 웹 서버 구현
      • CH03 MVC - @MVC 프레임워크 구현
        • Servlet 다시 짚기
        • Cookie, Session 다시 짚기
        • MVC 프레임워크 구현
      • CH04 나만의 라이브러리 구현
      • CH05 DI - DI 프레임워크 구현
      • CH06 Aspect OP
    • 스프링 시큐리티
      • 스프링 시큐리티 아키텍처
      • WebAsyncManagerIntegrationFilter
      • SecurityContextPersistenceFilter
      • HeaderWriterFilter
      • CsrfFilter
      • (+) 스프링 시큐리티 + JWT
      • (+) 마치며
    • 더 자바, 코드를 조작하는 다양한 방법
      • CH01 JVM 이해하기
      • (+) 클래스 로더 이해하기
      • CH02 바이트 코드 분석 및 조작
      • (+) jacoco
      • CH03 리플렉션
      • CH04 다이나믹 프록시
      • CH05 애노테이션 프로세서
    • 더 자바, 애플리케이션을 테스트하는 다양한 방법
      • CH01 JUnit 5
      • CH02 Mockito
      • (+) Spy vs Mock
      • CH03 도커와 테스트
      • CH04 성능 테스트
      • (+) VisualVM
      • (+) 테스트 자동화
      • CH05 운영 이슈 테스트
      • CH06 아키텍처 테스트
    • 모든 개발자를 위한 HTTP 웹 기본 지식
      • CH01 인터넷 네트워크
      • CH02 HTTP 기본
      • CH03 HTTP 메서드 속성
      • CH04 HTTP 메서드 활용
      • CH05 HTTP 상태코드
      • CH06 HTTP 헤더1 - 일반 헤더
      • CH07 HTTP 헤더2 - 캐시와 조건부 요청
      • (+) HTTPS 원리
    • 스프링 프레임워크 핵심 기술
      • CH01 IOC 컨테이너
      • CH02 AOP
      • (+) 스프링 의존성 관리
      • (+) 생성자 주입 장점
    • 코딩으로 학습하는 GoF의 디자인 패턴
      • 객체 생성
        • 싱글톤 패턴
        • 팩토리 메소드 패턴
        • 추상 팩토리 패턴
        • 빌더 패턴
        • 프로토타입 패턴
      • 구조
        • 어댑터 패턴
        • 브릿지 패턴
        • 컴포짓 패턴
      • 행동
        • (작성중)
    • 실전 Querydsl
      • CH01 프로젝트 환경구성
      • CH02 예제 도메인 모델
      • CH03 기본문법
      • CH04 중급 문법
      • CH05 실무활용 (스프링 데이터 JPA와 Querydsl)
      • CH06 스프링데이터JPA 가 제공하는 Querydsl 기능
      • (+) 별칭(alias)
      • (+) Slice 쿼리
    • 스프링 데이터 JPA
      • CH01 핵심개념이해 1
      • CH02 핵심개념이해 2
      • CH03 핵심개념이해 3
      • CH04 Spring Data Common
      • CH05 Spring Data JPA
    • 실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
      • CH01 지연 로딩과 조회 성능 최적화
      • CH02 컬렉션 조회 최적화
      • CH03 전체 정리
    • 초보를 위한 쿠버네티스 안내서
      • CH01 쿠버네티스 시작하기
      • CH02 쿠버네티스 알아보기
      • CH03 쿠버네티스 실습 준비
      • CH04 쿠버네티스 기본 실습
    • Flutter Provider Essential
      • CH01 Introduction
      • CH02 Provider Overview
      • CH03 TODO App
      • CH04 Weather App
      • CH05 Firebase Authentication App
    • Flutter Bloc Essential
      • CH01 Introduction
      • CH02 Bloc Overview
      • CH03 TODO App
      • CH04 Weather App
      • CH05 Firebase Authentication App
    • Flutter Advanced Course - Clean Architecture With MVVM
      • CH01 Introduction
      • CH02 Clean Architecture 4 Layer
      • CH03 MVVM
      • CH04 Data Layer
      • (+) Data Layer - response to model
      • (+) Data Layer - Network
      • CH05 Domain Layer
      • CH06 Presentation Layer
      • CH07 Application Layer
      • (+) Application Layer - l10n
      • (+) Application Layer - DI
      • (+) Application Layer - environment
    • 자바 알고리즘 입문
      • CH01 문자열
      • CH02 Array(1, 2 차원 배열)
      • CH03 Two pointers, Sliding window[효율성: O(n^2)-->O(n)]
      • CH04 HashMap, TreeSet (해쉬, 정렬지원 Set)
      • CH05 Stack, Queue(자료구조)
      • CH06 Sorting and Searching(정렬, 이분검색과 결정알고리즘)
      • CH07 Recursive, Tree, Graph(DFS, BFS 기초)
      • CH08 DFS, BFS 활용
      • CH09 Greedy Algorithm
      • CH10 dynamic programming(동적계획법)
  • 도서
    • 만들면서 배우는 클린 아키텍처
      • 학습목표
      • CH01 계층형 아키텍처의 문제는 무엇일까?
      • CH02 의존성 역전하기
      • CH03 코드 구성하기
      • CH04 유스케이스 구현하기
      • CH05 웹 어댑터 구현하기
      • CH06 영속성 어댑터 구현하기
      • CH07 아키텍처 요소 테스트하기
      • CH08 경계 간 매핑하기
      • CH09 어플리케이션 조립하기
      • CH10 아키텍처 경계 강제하기
      • CH11 의식적으로 지름길 사용하기
      • CH12 아키텍처 스타일 결정하기
    • 클린 아키텍처
      • 들어가며
      • 1부 소개
        • 1장 설계와 아키텍처란?
        • 2장 두 가지 가치에 대한 이야기
      • 2부 벽돌부터 시작하기: 프로그래밍 패러다임
        • 3장 패러다임 개요
        • 4장 구조적 프로그래밍
        • 5장 객체 지향 프로그래밍
        • 6장 함수형 프로그래밍
      • 3부 설계 원칙
        • 7장 SRP: 단일 책임 원칙
        • 8장 OCP: 개방-폐쇄 원칙
        • 9장 LSP: 리스코프 치환 원칙
        • 10장 ISP: 인터페이스 분리 원칙
        • 11장 DIP: 의존성 역전 원칙
      • 4부 컴포넌트 원칙
        • 12장 컴포넌트
        • 13장 컴포넌트 응집도
        • 14장 컴포넌트 결합
      • 5부
        • 15장 아키텍처란?
    • 스프링 입문을 위한 자바 객체 지향의 원리와 이해
      • CH01 사람을 사랑한 기술
      • CH02 자바와 절차적/구조적 프로그래밍
      • CH03 자바와 객체 지향
      • (+) 자바 코드 실행에 따른 메모리 적재과정
      • CH04 자바가 확장한 객체 지향
      • CH05 객체 지향 설계 5 원칙 - SOLID
      • CH06 스프링이 사랑한 디자인 패턴
      • CH07 스프링 삼각형과 설정 정보
      • (부록) 람다(lambda)
    • 객체지향의 사실과 오해
      • CH01 협력하는 객체들의 공동체
      • CH02 이상한 나라의 객체
      • CH03 타입과 추상화
      • CH04 역할, 책임, 협력
      • CH05 책임과 메시지
      • CH06 객체 지도
      • CH07 함께 모으기
      • (+) 인터페이스 개념 바로잡기
    • 도메인 주도 개발 시작하기
      • CH01 도메인 모델 시작하기
      • CH02 아키텍처 개요
      • CH03 애그리거트
      • CH04 리포지터리와 모델 구현
      • CH05 스프링 데이터 JPA를 이용한 조회 기능
      • CH06 응용 서비스와 표현 영역
      • CH07 도메인 서비스
      • CH08 애그리거트 트랜잭션 관리
      • CH09 도메인 모델과 바운디드 컨텍스트
      • CH10 이벤트
      • CH11 CQRS
    • 자바 ORM 표준 JPA 프로그래밍
      • CH01 JPA 소개
      • CH02 JPA 시작
      • CH03 영속성 관리
      • CH04 엔티티 매핑
      • CH05 연관관계 매핑 기초
      • CH06 다양한 연관관계 매핑
      • CH07 고급 매핑
      • CH08 프록시와 연관관계 관리
      • CH09 값 타입
      • CH10 객체지향 쿼리 언어
      • CH11 웹 애플리케이션 제작
      • CH12 스프링 데이터 JPA
      • CH13 웹 애플리케이션과 영속성 관리
      • CH14 컬렉션과 부가 기능
      • CH15 고급 주제와 성능 최적화
      • CH16 트랜잭션과 락, 2차 캐시
    • 소프트웨어 세상을 여는 컴퓨터과학
      • CH01 컴퓨터 과학 소개
      • CH02 데이터 표현과 디지털 논리
    • 이펙티브 자바
      • 1 장 들어가기
      • 2장 객체 생성과 파괴
        • [01] 생성자 대신 정적 팩터리 메서드를 고려하라
        • [02] 생성자에 매개변수가 많다면 빌더를 고려하라
        • [03] private 생성자나 열거 타입으로 싱글턴임을 보증하라
        • [04] 인스턴스화를 막으려거든 private 생성자를 사용하라
        • [05] 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라
        • [06] 불필요한 객체 생성을 피하라
        • [07] 다 쓴 객체 참조를 해제하라
        • [08] finalizer 와 cleaner 사용을 피하라
        • [09] try-finally 보다는 try-with-resources 를 사용하라
      • 3장 모든 객체의 공통 메서드
        • [10] equals는 일반 규약을 지켜 재정의하라
        • [11] equals 를 재정의하려거든 hashCode도 재정의하라
        • [12] toString 을 항상 재정의하라
        • [13] clone 재정의는 주의해서 진행하라
        • [14] Comparable 을 구현할지 고려하라
      • 4장 클래스와 인터페이스
        • [15] 클래스와 멤버의 접근 권한을 최소화하라
  • 토픽
    • 서버 모니터링
      • CPU 사용량
      • 메모리 사용량
      • 스레드 풀
    • Spring Boot Monitoring
      • Spring actuator
      • Spring eureka
      • Prometheus
      • grafana
      • Spring actuator + Prometheus + grafana
    • JAVA 데일리 토픽
      • 메모리 누수(memory leak)
      • 객체 참조의 유형
      • 커스텀 스레드 풀
      • Mark And Compact
      • serialVersionUID 이해하기
      • 함수형 인터페이스
      • 메소드 참조
      • equals()와 hashCode()가 무엇이고 역할이 무엇인지
      • StringBuffer vs StringBuilder
      • String vs StringBuilder, StringBuffer
      • String interning
    • JAVA GC
    • 프로그래머스 문제 풀기
      • 해시
      • 스택/큐
      • 힙(Heap)
      • 정렬
      • 완전탐색
      • DFS/BFS
    • 데이터베이스 구성 및 작동 흐름
    • 데이터베이스 JOIN 원리
    • 객체지향생활체조 원칙
    • 상태(state), 상속(inheritance), 합성(composition) 의 상관관계
    • java enum은 메모리에 언제, 어떻게 할당되는가
    • Checked Exception vs UnChecked Exception
    • Reactive Streams 원리탐구 - 간단한 예제 직접 작성해보기
    • Flutter Basic
    • Flutter StatefulWidget 생명주기
    • Flutter 가 위젯을 그리는 원리
    • Flutter 클린 아키텍처
      • application layer
        • 패키지 구조 및 레이어 설명
        • environment
        • dependency injection
        • go_router
        • foreground & background
        • 다국어처리 (l10n, i18n)
        • Global 처리(시스템 점검, fore->back 등)
        • connection_manager
        • permission_manager
        • push_notification_manager
        • firebase 연동
      • data layer
        • 패키지 구조 및 레이어 설명
        • network
        • repository
      • domain layer
        • 패키지 구조 및 레이어 설명
      • presentation layer
        • 패키지 구조 및 레이어 설명
        • resources
    • 기술 관련 포스팅 읽기
  • 기타
    • 작업일지
      • 2023. 10
      • 2023. 09
      • 2023. 08
      • 2023. 07
      • 2023. 06
      • 2023. 05
      • 2023. 04
      • 2023. 03
      • 2023. 02
      • 2023. 01
      • 2022. 12
    • Business Model
      • 아이디어 불패의 법칙
      • 린 모바일 앱 개발
      • 린 스타트업
      • 제로투원
      • MIT 스타트업 바이블
      • 린치핀
    • 백로그 종합
Powered by GitBook
On this page
  • 실습코드
  • 스프링에서 요청을 처리하는 전체 흐름
  • DispatcherServlet
  • ApplicationContext
  • HandlerMapping
  • HandlerAdapter
  • ArgumentResolver
  • ViewResolver
  1. 강의
  2. NEXTSTEP 만들면서 배우는 Spring 3기
  3. CH03 MVC - @MVC 프레임워크 구현

MVC 프레임워크 구현

PreviousCookie, Session 다시 짚기NextCH04 나만의 라이브러리 구현

Last updated 1 year ago

링크참고

스프링에서 요청을 처리하는 전체 흐름

코드로 이걸 구현하는 것이기에 일단 코드를 보기 전에 전체 흐름을 짚고 넘어간다. 아래 두 그림을 보자.

2번 그림이 더 세밀하게 잘 나와있어서 좋은데 필터 관련 그림이 없어서 1번 그림까지 같이 추가를 했다. 사실 이번 구현의 핵심은 2번 그림을 자세히 구현하는 것이다. 흐름 별로 하나씩 코드를 살펴보면서 어떻게 구현하였는지, 원리는 어떠한지를 정리한다.

'MVC 프레임워크 구현' 에서는 원리를 중점적으로 알아보는게 목적이라서 실제 코드가 위 그림과 약간은 다를 수 있다. 실제 스프링과 클래스 명까지 같게 구현하는 것은 'DI 프레임워크 구현' 에서 했고 'DI 프레임워크 구현' 에서 위 그림을 두고 다시 한번 더 정리할 예정이다.

그래서 이번 'MVC 프레임워크 구현' 에서는 각 역할을 어떻게 구현했고 원리가 무엇인지에 대해서 더 집중해서 살펴보면 좋을 것 같다.

DispatcherServlet

이건 기존 자바지기님 코드에 내가 필요한 부분을 리팩토링 하는 형식으로 미션이 진행되었다. 핵심적인 부분만 코스 수강자들이 처리하도록 하고 나머지는 이미 구현을 해둔 상태의 레포지토리를 받아서 수정하면서 진행하는 방식이다.

    @Override
    public void init() throws ServletException {
        ApplicationContext.getInstance().init();
        AnnotationHandlerMapping.getInstance().init();
    }

여기 사용된 ApplicationContext 부터 살펴보자.

ApplicationContext

public class ApplicationContext {

    private static final ApplicationContext applicationContext = new ApplicationContext();
    private final ComponentScanner componentScanner = ComponentScanner.getInstance();
    private final Map<String, Object> beans = new HashMap<>();

    private ApplicationContext() {

    }

    public static ApplicationContext getInstance() {
        return applicationContext;
    }

    public void init() {
        Set<Class<?>> clazzSet = componentScanner.getComponents();
        clazzSet.forEach(clazz -> {
            String name = clazz.getName();
            beans.put(name, this.constructInstance(clazz));
        });
    }

    public Object getBean(String name) {
        return this.beans.get(name);
    }

    public Map<String, Object> getBeans() {
        return beans;
    }

    private Object constructInstance(Class<?> clazz) {
        try {
            return clazz.getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}

리플렉션을 이용해서 생성자를 가져와서 인스턴스를 만들고 이를 beans 에 넣어둔다. 컴포넌트 스캔을 해서 bean 생성을 하는 것이다. 지금은 파라미터도 없는 단순한 형태인데 나중에 'DI 프레임워크 구현' 에서 실제로 스프링에서 동작하는 의존성 주입의 방식을 재현한다.

HandlerMapping

public class AnnotationHandlerMapping implements HandlerMapping {

    private final Map<HandlerKey, HandlerExecution> handlerExecutions = Maps.newHashMap();

    private static final AnnotationHandlerMapping annotationHandlerMapping = new AnnotationHandlerMapping();

    public static AnnotationHandlerMapping getInstance() {
        return annotationHandlerMapping;
    }

    @Override
    public void init() {
        Map<String, Object> controllers = ApplicationContext.getInstance().getBeans();
        controllers.values()
                .forEach(this::setHandlerExecutions);
    }

    @Override
    public Object getHandler(HandlerKey handlerKey) {
        String requestUri = handlerKey.getUri();
        Object handler = handlerExecutions.get(handlerKey);
        if (Objects.nonNull(handler)) {
            return handler;
        }

        return handlerExecutions.entrySet().stream()
                .filter(entry -> {
                    String handlerUri = entry.getKey().getUri();
                    RequestMethod requestMethod = entry.getKey().getRequestMethod();
                    return (PathAnalyzer.isSamePattern(handlerUri, requestUri)) && (handlerKey.getRequestMethod().equals(requestMethod));
                })
                .map(Map.Entry::getValue)
                .findAny()
                .orElse(null);
    }

    public String getHandlerOriginUri(String requestUri) {
        return handlerExecutions.keySet().stream()
                .filter(handlerExecution -> {
                    String handlerUri = handlerExecution.getUri();
                    return PathAnalyzer.isSamePattern(handlerUri, requestUri);
                })
                .map(HandlerKey::getUri)
                .findAny()
                .orElse(null);
    }

    private void setHandlerExecutions(Object controller) {
        List<Method> methods = Arrays.stream(controller.getClass().getDeclaredMethods())
                .filter(method -> this.hasRequestMapping(method.getDeclaredAnnotations()))
                .collect(Collectors.toList());

        methods.forEach(method -> this.setHandlerExecution(method, controller));
    }

    private boolean hasRequestMapping(Annotation[] annotations) {
        return Arrays.stream(annotations)
                .anyMatch(annotation -> annotation.annotationType().equals(RequestMapping.class));
    }

    private void setHandlerExecution(Method method, Object ownerInstance) {
        Annotation requestMapping = Arrays.stream(method.getDeclaredAnnotations())
                .filter(annotation -> annotation.annotationType().equals(RequestMapping.class))
                .findAny()
                .orElseThrow(IllegalArgumentException::new);

        String url = this.getUrl(requestMapping);
        RequestMethod requestMethod = this.getMethod(requestMapping);
        if (Objects.isNull(url) || Objects.isNull(requestMethod)) {
            throw new IllegalArgumentException();
        }

        HandlerKey handlerKey = new HandlerKey(url, requestMethod);
        HandlerExecution handlerExecution = new HandlerExecution(ownerInstance, method);
        this.handlerExecutions.put(handlerKey, handlerExecution);
    }

    private String getUrl(Annotation requestMapping) {
        Class<?> clazz = requestMapping.annotationType();
        Method pathMethod = Arrays.stream(clazz.getDeclaredMethods())
                .filter(method -> method.getName().equals("value"))
                .findAny()
                .orElseThrow(IllegalArgumentException::new);

        try {
            return String.valueOf(pathMethod.invoke(requestMapping));
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

    private RequestMethod getMethod(Annotation requestMapping) {
        Class<?> clazz = requestMapping.annotationType();
        Method pathMethod = Arrays.stream(clazz.getDeclaredMethods())
                .filter(method -> method.getName().equals("method"))
                .findAny()
                .orElseThrow(IllegalArgumentException::new);

        try {
            return (RequestMethod) pathMethod.invoke(requestMapping);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

}

이건 DispatcherServlet 에서 아래 코드를 사용할때 필요하다.

private Object findHandler(HandlerKey handlerKey) throws ServletException {
    Object handler = AnnotationHandlerMapping.getInstance().getHandler(handlerKey);
    if (Objects.isNull(handler)) {
        throw new ServletException();
    }

    return handler;
}

간단한 문장으로 정리하자면 AnnotationHandlerMapping 에서 적절한 핸들러를 찾아 주는 것이다.

@Override
public void init() {
    Map<String, Object> controllers = ApplicationContext.getInstance().getBeans();
    controllers.values()
            .forEach(this::setHandlerExecutions);
}

init 에서 기존에 ApplicationContext 에서 만든 bean들을 컨트롤러로 순회시키면서 아래와 같이 Handler 로 저장한다.

private void setHandlerExecutions(Object controller) {
    List<Method> methods = Arrays.stream(controller.getClass().getDeclaredMethods())
            .filter(method -> this.hasRequestMapping(method.getDeclaredAnnotations()))
            .collect(Collectors.toList());

    methods.forEach(method -> this.setHandlerExecution(method, controller));
}

private boolean hasRequestMapping(Annotation[] annotations) {
    return Arrays.stream(annotations)
            .anyMatch(annotation -> annotation.annotationType().equals(RequestMapping.class));
}

private void setHandlerExecution(Method method, Object ownerInstance) {
    Annotation requestMapping = Arrays.stream(method.getDeclaredAnnotations())
            .filter(annotation -> annotation.annotationType().equals(RequestMapping.class))
            .findAny()
            .orElseThrow(IllegalArgumentException::new);

    String url = this.getUrl(requestMapping);
    RequestMethod requestMethod = this.getMethod(requestMapping);
    if (Objects.isNull(url) || Objects.isNull(requestMethod)) {
        throw new IllegalArgumentException();
    }

    HandlerKey handlerKey = new HandlerKey(url, requestMethod);
    HandlerExecution handlerExecution = new HandlerExecution(ownerInstance, method);
    this.handlerExecutions.put(handlerKey, handlerExecution);
}

메소드가 핸들러가 아닌 메소드가 있을 수 있으므로 어노테이션을 이용해서 핸들러가 아닌 것과 핸들러인 것들을 구분하는 것을 1차로 실행하고 url 과 method 를 분석해서 적절한 요청에 대한 적절한 핸들러를 구분해서 Map 에 저장한다.

public HandlerKey(String uri, RequestMethod requestMethod) {
    this.uri = uri;
    this.requestMethod = requestMethod;
}

HandlerKey는 위와 같이 정의되어 있다. 이를 활용해서 '요청' 의 고유함을 정의하고 이를 기준으로 적절한 핸들러를 찾는다.

HandlerAdapter

다시 언급하지만 이번 'MVC 프레임워크 구현'은 원리를 그대로 따랐을 뿐 클래스 명은 실제 스프링과는 조금씩 상이하다.

아래 코드는 DispatcherServlet 코드인데 흐름이 너무 길어서 다시 짚고자 첨부했다. 현재 들어온 요청에 대해서 적절한 handler 를 찾는 과정까지 왔다.

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String requestUri = req.getRequestURI();
    logger.debug("Method : {}, Request URI : {}", req.getMethod(), requestUri);

    HandlerKey handlerKey = new HandlerKey(requestUri, RequestMethod.getRequestMethod(req.getMethod()));
    Object handler = this.findHandler(handlerKey);
    HandlerSpec handlerSpec = new HandlerSpec(handler, handlerKey, req, resp);
    try {
        ModelAndView modelAndView = ArgumentResolver.getInstance().invokeHandler(handlerSpec);
        modelAndView.render(req, resp);
    } catch (Throwable e) {
        logger.error("Exception : {}", e);
        throw new ServletException(e.getMessage());
    }
}

ArgumentResolver


public class ArgumentResolver {

    private final static ArgumentResolver argumentResolver = new ArgumentResolver();
    private final static Integer HANDLER_ARGUMENT_ANNOTATION_COUNT_LIMIT = 1;

    private ArgumentResolver() {

    }

    public static ArgumentResolver getInstance() {
        return argumentResolver;
    }

    public ModelAndView invokeHandler(HandlerSpec handlerSpec) throws Exception {
        HandlerExecution handlerExecution = (HandlerExecution) handlerSpec.getHandler();
        Method handler = handlerExecution.getMethod();

        List<Object> parameters = this.getParameters(handler.getParameters(), handlerSpec);
        return handlerExecution.handle(parameters);
    }

    public List<Object> getParameters(Parameter[] parameters, HandlerSpec handlerSpec) {
        return Arrays.stream(parameters)
                .map(parameter -> {
                    Annotation parameterAnnotation = this.getAnnotation(parameter);
                    try {
                        return this.getConvertedParameter(parameterAnnotation, parameter, handlerSpec);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());

    }

    private Object getConvertedParameter(Annotation parameterAnnotation, Parameter parameter, HandlerSpec handlerSpec) throws JsonProcessingException {
        HttpServletRequest httpServletRequest = handlerSpec.getHttpServletRequest();
        Class<?> parameterClass = parameter.getType();
        String parameterName = parameter.getName();

        if (parameterClass.getName().equals("javax.servlet.http.HttpServletRequest")) {
            return httpServletRequest;
        }

        if (Objects.isNull(parameterAnnotation)) {
            return this.getConvertedParamter(parameterClass, httpServletRequest.getParameter(parameterName));
        }

        if (parameterAnnotation.annotationType().equals(RequestBody.class)) {
            Map<String, String> parametersFromRequest = this.getParametersFromRequest(httpServletRequest, parameterClass);
            String data = ObjectMapperFactory.getObjectMapper().writeValueAsString(parametersFromRequest);
            return ObjectMapperFactory.getObjectMapper().readValue(data, parameterClass);
        }

        if (parameterAnnotation.annotationType().equals(PathVariable.class)) {
            String requestUri = httpServletRequest.getRequestURI();
            String handlerUri = AnnotationHandlerMapping.getInstance().getHandlerOriginUri(requestUri);
            return this.getPathVariable(requestUri, handlerUri, parameterName);
        }

        throw new IllegalArgumentException();
    }

    private Map<String, String> getParametersFromRequest(HttpServletRequest httpServletRequest, Class<?> parameterClass) {
        List<String> keys = Arrays.stream(parameterClass.getDeclaredFields())
                .map(Field::getName)
                .collect(Collectors.toList());

        Map<String, String> parametersFromRequest = new HashMap<>();
        keys.forEach(key -> {
            String value = httpServletRequest.getParameter(key);
            parametersFromRequest.put(key, value);
        });

        return parametersFromRequest;
    }

    private Object getConvertedParamter(Class<?> parameterClass, String value) {
        if (parameterClass.equals(int.class)) {
            return Integer.parseInt(value);
        }

        return value;
    }

    private Annotation getAnnotation(Parameter parameter) {
        Annotation[] annotations = parameter.getDeclaredAnnotations();
        if (annotations.length > HANDLER_ARGUMENT_ANNOTATION_COUNT_LIMIT) {
            throw new IllegalArgumentException();
        }

        return Arrays.stream(parameter.getDeclaredAnnotations())
                .findFirst()
                .orElse(null);
    }

    private String getPathVariable(String requestUri, String handlerUri, String targetParameter) {
        return PathAnalyzer.getVariables(handlerUri, requestUri, targetParameter);
    }

}

public ModelAndView invokeHandler(HandlerSpec handlerSpec) throws Exception {
    HandlerExecution handlerExecution = (HandlerExecution) handlerSpec.getHandler();
    Method handler = handlerExecution.getMethod();

    List<Object> parameters = this.getParameters(handler.getParameters(), handlerSpec);
    return handlerExecution.handle(parameters);
}

이미 요청을 처리할 handler 를 찾는건 해놨으므로 이제 요청에 들어온 파라미터를 handler 가 받을 수 있는 형태로 변환해서 handler 에 전달 후 handler 를 call 하는 것이 필요하다. 위 코드는 이 과정을 나타내고 있다.

public List<Object> getParameters(Parameter[] parameters, HandlerSpec handlerSpec) {
    return Arrays.stream(parameters)
            .map(parameter -> {
                Annotation parameterAnnotation = this.getAnnotation(parameter);
                try {
                    return this.getConvertedParameter(parameterAnnotation, parameter, handlerSpec);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());

}

private Object getConvertedParameter(Annotation parameterAnnotation, Parameter parameter, HandlerSpec handlerSpec) throws JsonProcessingException {
    HttpServletRequest httpServletRequest = handlerSpec.getHttpServletRequest();
    Class<?> parameterClass = parameter.getType();
    String parameterName = parameter.getName();

    if (parameterClass.getName().equals("javax.servlet.http.HttpServletRequest")) {
        return httpServletRequest;
    }

    if (Objects.isNull(parameterAnnotation)) {
        return this.getConvertedParamter(parameterClass, httpServletRequest.getParameter(parameterName));
    }

    if (parameterAnnotation.annotationType().equals(RequestBody.class)) {
        Map<String, String> parametersFromRequest = this.getParametersFromRequest(httpServletRequest, parameterClass);
        String data = ObjectMapperFactory.getObjectMapper().writeValueAsString(parametersFromRequest);
        return ObjectMapperFactory.getObjectMapper().readValue(data, parameterClass);
    }

    if (parameterAnnotation.annotationType().equals(PathVariable.class)) {
        String requestUri = httpServletRequest.getRequestURI();
        String handlerUri = AnnotationHandlerMapping.getInstance().getHandlerOriginUri(requestUri);
        return this.getPathVariable(requestUri, handlerUri, parameterName);
    }

    throw new IllegalArgumentException();
}

이것도 간단하게 한 문장으로 정리하자면 '어노테이션을 분석해서 적절하게 변환 처리를 해준다' 가 전부이다. 리플렉션을 적극적으로 활용해서 구현했다.

이렇게 '바퀴를 직접 다시 만드는' 과정을 통해서 기존 바퀴가 얼마나 대단하고 잘 만들어져있는가를 잘 알 수 있고, 기존 바퀴에 대한 이해를 깊게 만들 수 있었다.

ViewResolver

public ModelAndView invokeHandler(HandlerSpec handlerSpec) throws Exception {
    HandlerExecution handlerExecution = (HandlerExecution) handlerSpec.getHandler();
    Method handler = handlerExecution.getMethod();

    List<Object> parameters = this.getParameters(handler.getParameters(), handlerSpec);
    return handlerExecution.handle(parameters);
}

위 코드를 보면 HandlerExecution 이라는 것이 있는데 아래와 같다.

public class HandlerExecution {

    private final Object locatedInstance;
    private final Method method;

    public HandlerExecution(Object locatedInstance, Method method) {
        this.locatedInstance = locatedInstance;
        this.method = method;
    }

    public ModelAndView handle(List<Object> parameters) throws Exception {
        if (parameters.isEmpty()) {
            return (ModelAndView) method.invoke(locatedInstance);
        }

        if (parameters.size() == 1) {
            return (ModelAndView) method.invoke(locatedInstance, parameters.get(0));
        }

        if (parameters.size() == 2) {
            return (ModelAndView) method.invoke(locatedInstance, parameters.get(0), parameters.get(1));
        }

        if (parameters.size() == 3) {
            return (ModelAndView) method.invoke(locatedInstance, parameters.get(0), parameters.get(1), parameters.get(2));
        }

        if (parameters.size() == 4) {
            return (ModelAndView) method.invoke(locatedInstance, parameters.get(0), parameters.get(1), parameters.get(2), parameters.get(3));
        }

        // TODO handler parameter 더 많은 경우
        throw new IllegalArgumentException();
    }

    public Method getMethod() {
        return method;
    }
}

지금 봐도 완성도가 썩 마음에 들진 않는다. 내가 'MVC 프레임워크 구현' 에서 만든 MVC 프레임워크는 위 코드처럼 파라미터가 5개 이상이면 에러가 나는 프레임워크인 것이다.(아무튼 원리 이해가 목적이다)

여기서 짚고 넘어가고 싶은 것은 모든 핸들러의 응답을 ModelAndView 으로 강제했다는 점이다. 일단 여기서는 하나의 타입으로 강제하고 내부 구현체가 세부 로직을 담당한다.

@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView modelAndView = ModelAndView.getJspModelAndView("home.jsp");
        modelAndView.addObject("users", DataBase.findAll());
        return modelAndView;
    }

}

핸들러 하나를 예시로 가져왔다. 위와 같이 ModelAndView 를 반환한다. 모든 핸들러가 ModelAndView 를 반환하도록 처리해뒀기 때문에 HandlerExecution 에서 모두 ModelAndView 로 캐스팅 할 수 있다.

public class ModelAndView {
    private View view;
    private final Map<String, Object> model = new HashMap<>();

    public ModelAndView() {
    }

    public ModelAndView(View view) {
        this.view = view;
    }

    public static ModelAndView getJspModelAndView(String viewName) {
        return new ModelAndView(new JspView(viewName));
    }

    public static ModelAndView redirectHome() {

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

    public ModelAndView addObject(String attributeName, Object attributeValue) {
        model.put(attributeName, attributeValue);
        return this;
    }

    public Object getObject(String attributeName) {
        return model.get(attributeName);
    }

    public Map<String, Object> getModel() {
        return Collections.unmodifiableMap(model);
    }

    public View getView() {
        return view;
    }

    public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.view.render(model, request, response);
    }
}

내부에서 View 를 가지고 있다. 이건 굳이 패턴으로 치면 브릿지 패턴이다. 내부에서 View 라는 추상을 가지고 있고 이것의 구체적인 구현은 따로 빼서 구현체가 처리하며 객체 자체는 추상만 프로퍼티로 지니고 있다.

public static ModelAndView getJspModelAndView(String viewName) {
    return new ModelAndView(new JspView(viewName));
}

핸들러에서 만들어준 JspView 를 보자.

public class JspView implements View {

    private final String viewName;

    public JspView(String viewName) {
        this.viewName = viewName;
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ViewRenderer.getInstance().render(viewName, request, response);
    }

}
public class ViewRenderer {
    private static final String DEFAULT_REDIRECT_PREFIX = "redirect:";

    private static final ViewRenderer viewRenderer = new ViewRenderer();

    private ViewRenderer() {

    }

    public static ViewRenderer getInstance() {
        return viewRenderer;
    }

    public void render(String viewName, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        move(viewName, req, resp);
    }

    private void move(String viewName, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        if (viewName.startsWith(DEFAULT_REDIRECT_PREFIX)) {
            resp.sendRedirect(viewName.substring(DEFAULT_REDIRECT_PREFIX.length()));
            return;
        }

        RequestDispatcher rd = req.getRequestDispatcher(viewName);
        rd.forward(req, resp);
    }

}

위와 같이 viewName 을 기준으로 view 를 찾아서 응답으로 내보내게 된다.

실습코드