HttpServletResponse - 기본 사용법

HttpServletRespons로 HTTP 응답 메시지를 생성할 수 있다!

  1. HTTP 응답 코드 지정

  2. 헤더 생성 - content, cookie, redirect

  3. 바디 생성 - message body

Content 편의 메서드

private void content(HttpServletResponse response){
        //Content-Type : text/plain;charset=utf-8
        //Content-Length : 2
        response.setHeader("Content-Type", "text/plain;charset-utf-8");
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        //response.setContentLength(2);생략 시 자동 생성
    }

쿠키 메서드

private void cookie(HttpServletResponse response) {
  //Set-Cookie: myCookie=good; Max-Age=600;
  //response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
  Cookie cookie = new Cookie("myCookie", "good");
  cookie.setMaxAge(600); //600초
  response.addCookie(cookie);
}

redirect 메서드

private void redirect(HttpServletResponse resp) throws IOException {
        //Status Codee 302
        //Location: /basic/hello-form.html

//        resp.setStatus(resp.SC_FOUND);//302
//        resp.setHeader("Location","/basic/hello-form.html");
        resp.sendRedirect("/basic/hello-form.html");
    }

Last updated