httpServlet response

su dong·2023년 6월 20일
0

httpServlet response 응답

응답메세지를 생성한다!

HTTP 응답코드 지정(200,400,500등등)

응답 헤더 생성

  • 쿠키 보내주기
  • 리다이렉션

응답 바디 생성

HTTP 응답 코드 생성

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

        //[response-header]
        response.setHeader("Content-Type","text/plain;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("my-header","hello");

        response.getWriter().write("ok");
    }
}

응답 데이터

- 텍스트

response.getWriter().write("ok");

- html

response.setContentType("text/html");
 response.setCharacterEncoding("utf-8");
 PrintWriter writer = response.getWriter();
 writer.println("<html>");
 writer.println("<body>");
 writer.println(" <div>안녕?</div>");
 writer.println("</body>");
 writer.println("</html>");

- api

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

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter writer = response.getWriter();
        HelloData helloData = new HelloData();
        helloData.setUsername("park");
        helloData.setAge(29);

        String result = objectMapper.writeValueAsString(helloData);
        response.getWriter().write(result);

    }
}
profile
사람들을 돕는 문제 해결사, 개발자 sudong입니다. 반갑습니다. tkddlsqkr21@gmail.com

0개의 댓글