프로젝트/개인 프로젝트

[Java/Spring] HttpServletResponse의 역할

go_getter 2025. 4. 4. 11:44

HttpServletResponse가 API 파라미터로 존재하는 이유

서버는 클라이언트로 응답할 때, return을 통해 View, String, ResponseEntity(JSON)를 전달하거나 HttpServletResponse를 사용해서 응답 데이터(Body, Headers, Cookies 등)를 설정하고 전달할 수 있다.

 

@PostMapping("/login")
public ResponseEntity<LoginResponseDto> login(
    @Valid @RequestBody LoginRequestDto requestDto, 
    HttpServletResponse response) {
    
    LoginResponseDto responseDto = userService.login(requestDto);

    // 로그인 성공하면 쿠키 설정
    Cookie cookie = new Cookie("userId", String.valueOf(responseDto.getId()));
    response.addCookie(cookie); // 응답 객체 활용

    return new ResponseEntity<>(responseDto, HttpStatus.OK);
}

 

이 코드를 보면, HttpServletResponse가 login 메서드의 파라미터로 전달되고 있다.

Response는 서버에서 클라이언트로 응답할 때 사용하는데 왜 파라미터로 전달되는 것일까?

 

이유는 HttpServletResponse가 단순히 데이터가 아니라, 클라이언트의 요청과 1:1로 연결된 응답 객체이기 때문이다.

Spring이 HttpServletResponse 객체를 자동으로 주입해주고, 개발자가 이 객체를 조작하면 그 결과가 클라이언트에게 응답으로 전달된다.

개발자가 설정한 값을 클라이언트에 반환하는 것도 Spring이 자동으로 해주기 때문에 따로 return할 필요가 없다.

 

@PostMapping("/hello")
public ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello, Client!");
}

 

이렇게 파라미터로 HttpServletResponse가 주어지지 않은 경우에도 Spring은 내부적으로 응답 객체를 전달하고 있다.

개발자가 따로 응답 객체인 HttpServletResponse를 조작하지 않아서 Spring이 알아서 처리하고 클라이언트로 함께 전달한다.

 

 

HttpServletResponse의 주요 기능

1. 응답 상태 코드 설정

response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400 Bad Request

// Spring에서는 ResponseEntity, @ResponseStatus를 사용하는 게 더 간편

 

2. 응답 헤더 설정

response.setHeader("Cache-Control", "no-cache");
response.addHeader("Custom-Header", "value");
// Spring에서는 ResponseEntity로 대체 가능

return ResponseEntity.ok()
    .header("Cache-Control", "no-cache")
    .header("Custom-Header", "value")
    .body("Hello!");

 

3. 쿠키 추가

Cookie cookie = new Cookie("userId", "12345");
cookie.setHttpOnly(true);
cookie.setPath("/");
response.addCookie(cookie);

 

4. 리디렉션

response.sendRedirect("/home");

 

5. 파일 다운로드

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"example.pdf\"");
OutputStream out = response.getOutputStream();
byte[] fileData = Files.readAllBytes(Paths.get("example.pdf"));
out.write(fileData);
out.flush();

 

 


쿠키는 HttpServletRepsonse가 필요하지만, 세션은 HttpServletRequest만 필요한 이유

아래 코드는 동일한 메서드에서 세션을 적용한 예시이다.

쿠키를 사용하기 위해서 HttpServletResponse를 파라미터로 전달받아 쿠키를 설정해야 했는데,

세션은 HttpServletRequest를 전달받고 있다.

public ResponseEntity<LoginResponseDto> login
	(@Valid @RequestBody LoginRequestDto requestDto, 
       HttpServletRequest request){
        
        LoginResponseDto responseDto = userService.login(requestDto);

        HttpSession session = request.getSession(); // 세션 할당

        UserResponseDto loginUser = new UserResponseDto(responseDto.getId(), userService.findById(responseDto.getId()));
        session.setAttribute(LOGIN_USER, loginUser);

        return new ResponseEntity<>(responseDto, HttpStatus.OK);
    }

 

쿠키는 개발자가 쿠키 객체를 생성하고 addCookie()로 response 객체에 쿠키를 담아줘야 했다.

반면에 세션은 request로 전달받은 객체에서 getSession()으로 세션 정보만 꺼내서 서버에서 관리한다.

 

즉, 쿠키는 클라이언트에서 관리하고 세션은 서버에서 관리하기 때문에 이러한 차이가 있다고 볼 수 있다.