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
반응형
'Spring > spring framework 구현 스터디' 카테고리의 다른 글
[Spring] MVC 패턴 (0) | 2021.10.12 |
---|---|
[Spring] 서블릿, JSP 예제 (0) | 2021.10.11 |
[Spring] Servlet 다루기 2: HttpServletRequest 예제 (0) | 2021.10.10 |
[Spring] Servlet 다루기 1: Servlet, HttpServletRequest (0) | 2021.10.09 |
[Spring] 멀티 쓰레드 (0) | 2021.10.05 |
댓글