본문 바로가기
교재 실습/자바 웹 프로그래밍 Next Step

5.1.2.2 응답 데이터를 처리하는 로직을 별도의 클래스로 분리한다(HttpResponse)

by Jint 2025. 3. 17.
HINT · RequestHandler 클래스를 보면 응답 데이터 처리를 위한 많은 중복이 있다. 이 중복을 제거해 본다.
· 응답 헤더 정보를 Map<String, String>으로 관리한다.
· 응답을 보낼 때 HTML, CSS, 자바스크립트 파일을 직접 읽어 응답으로 보내는 메서드는 forward(), 다른 URL로 리다이렉트하는 메서드는 sendRedirect() 메서드를 나누어 구현한다.

 

요청 데이터에 대한 처리를 담당하고 있는 HttpResponse가 정상적으로 동작하는지 다음과 같은 테스트 코드를 통해 확인할 수 있다.

 

- src/test/java/http/HttpResponseTest.java

package http;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.junit.Test;

public class HttpResponseTest {

    private String testDirectory = "./src/test/resources/";

    @Test
    public void responseForward() throws Exception {
        // Http_Forward.txt 결과는 응답 body에 index.html이 포함되어 있어야 한다.
        HttpResponse response = new HttpResponse(createOutputStream("Http_Forward.txt"));
        response.forward("/index.html");
    }

    @Test
    public void responseRedirect() throws Exception {
        // Http_Redirect.txt 결과는 응답 header에 Location 정보가 /index.html로 포함되어 있어야 한다.
        HttpResponse response = new HttpResponse(createOutputStream("Http_Redirect.txt"));
        response.sendRedirect("/index.html");
    }

    @Test
    public void responseCookies() throws Exception {
        // Http_Cookie.txt 결과는 응답 header에 Set-Cookie 값으로 logined=true 값이 포함되어 있어야 한다.
        HttpResponse response = new HttpResponse(createOutputStream("Http_Cookie.txt"));
        response.addHeader("Set-Cookie", "logined=true");
        response.sendRedirect("/index.html");
    }

    private OutputStream createOutputStream(String filename) throws FileNotFoundException {
        return new FileOutputStream(new File(testDirectory + filename));
    }

}

 

HttpResponseTest 코드는 HttpResponse를 통해 생성된 응답 데이터를 src/test/resources에 파일을 생성해 수동으로 확인하도록 구현하고 있다. 수동으로 확인하는 번거로움이 있지만 HttpResponse를 다른 클래스에서 사용하기 전에 정상적으로 동작하는지 검증할 수 있다. 만약 이 같은 수동 테스트가 만족스럽지 않다면 assertEquals()를 통해 자동화할 수 있는 방법을 찾아본다.

지금까지 요구사항을 구현했을 때의 결과를 클래스 다이어그램(IntelliJ IDEA 통합 개발 도구에서 제공하는 UML 도구를 활용할 수 있음)으로 그려보면 다음과 같다.

 

클래스 다이어그램

 

 

클래스 다이어그램과 관련한 설명은 다음 요구사항에 대한 결과를 클래스 다이어그램으로 살펴본 후 같이 설명한다.



참고도서 : https://roadbook.co.kr/169

 

[신간안내] 자바 웹 프로그래밍 Next Step

● 저자: 박재성 ● 페이지: 480 ● 판형: 사륙배변형(172*225) ● 도수: 1도 ● 정가: 30,000원 ● 발행일: 2016년 9월 19일 ● ISBN: 978-89-97924-24-0 93000 [강컴] [교보] [반디] [알라딘] [예스24] [인터파크] [샘

roadbook.co.kr

댓글