반응형
HttpServletResponse 역할
- HTTP 응답 메시지를 쉽게 생성할 수 있게 도아준다.(HTTP 응답코드, 헤더, 바디 등을 생성)
- 편의 기능 제공(Content-Type, 쿠키, Redirect)
- START LINE, 헤더 생성
더보기
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//[status-line]
response.setStatus(HttpServletResponse.SC_OK);
//[response-headers]
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");
}
- 헤더 편의 메서드
더보기
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);
}
더보기
// 리다이렉트
private void redirect(HttpServletResponse response) throws IOException {
//Status Code 302
//Location: /basic/hello-form.html
//response.setStatus(HttpServletResponse.SC_FOUND); //302
//response.setHeader("Location", "/basic/hello-form.html");
response.sendRedirect("/basic/hello-form.html");
}
HTTP 응답 데이터
1. 단순 텍스트 응답
더보기
PrintWriter writer = response.getWriter();
writer.println("안녕하세요");
2. HTML 응답
- HTML을 반환할 때는 content-type을 text/html로 지정해야 함!
더보기
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
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>");
}
3. API JSON
- JSON 파싱 라이브러리인 Jackson이 제공하는 ObjectMapper을 사용
- objectMapper().writeValueAsString()을 사용하여 객체를 Json 문자로 변경할 수 있다.
더보기
@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");
HelloData helloData = new HelloData();
helloData.setUsername("kim");
helloData.setAge(20);
String result = objectMapper.writeValueAsString(helloData);
response.getWriter().write(result);
}
}
----------------------------------------
참고 : 인프런 김영한님 강의(스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술)
댓글