Free Lines Arrow
본문 바로가기
Spring/spring framework 구현 스터디

[Spring] Servlet 다루기 3: HttpServletResponse 예제

by skahn1215 2021. 10. 11.
728x90
반응형

HttpServletResponse 

response 를 다뤄보자

 

 

역할

  • HTTP 응답 메시지 생성
  • 헤더생성
  • 바디생성

 

제공되는 기능

쿠키, Redirect, Content-Type

 

 

 

기본예제

content, cookie, redirct 의 경우 편하게 set 할수 있는 메서드가 제공된다.

@WebServlet(name = "responseHeaderServlet", urlPatterns = "/response-header")
public class ResponseHeaderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // [status-line]
        resp.setStatus(HttpServletResponse.SC_OK);

        // [response-header]
        resp.setHeader("Pragma","no-cache");
        resp.setHeader("my-header","hello");

        content(resp);
        cookie(resp);

        // redirect
        redirect(resp);

        PrintWriter writer = resp.getWriter();
        writer.write("OK");
    }

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

    private void cookie(HttpServletResponse res) {
        //Set-Cookie: myCookie=good; Max-Age=600
        //response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
        Cookie cookie = new Cookie("muCookie","good");
        cookie.setMaxAge(600); // 600초 동안 유효하다.
        res.addCookie(cookie);
    }

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

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

 

 

HTML 으로 응답하기

@WebServlet(name = "responseHtmlServlet", urlPatterns = "/response-html")
public class ResponseHtmlServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 컨텐츠 타입을 보고 HTML 인지 판단한다.
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");

        PrintWriter writer = resp.getWriter();
        writer.println("<html>");
        writer.println("<body>");
        writer.println("    <div>안녕?</div>");
        writer.println("</body>");
        writer.println("</html>");
    }
}

 

 

 

JSON으로 응답하기

@WebServlet(name = "responseJsonServlet", urlPatterns = "/response-json")
public class ResponseJsonServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");

        HelloData data = new HelloData();
        data.setUsername("ahn");
        data.setHobby("Drum");

        // object -> json

        // object 를 문자로 변경해라.
        String result = objectMapper.writeValueAsString(data);
        resp.getWriter().write(result);

    }
}

 

 

728x90
반응형

댓글