HttpServletRequest
HTTP 요청 메시지를 파싱하고 결과를 HttpServletRequest 객체에 담아 제공
POST /save HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
username=kim&age=20
request.setAttribute(name, value) //저장
request.getAttribute(name) //조회
request.getSession(create: true)
start-line 정보
.getMethod() = GET
.getProtocol() = HTTP/1.1
.getScheme() = http
.getRequestURL() = http:localhost:8080/request-header
.getRequestURI() = /request-header
.getQueryString() = username=hello
.isSecure() = false //https 사용 유무
header 모든 정보
예전 문법
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + request.getHeader(headerName));
}
요즘 문법
request.getHeaderNames().asIterator()
.forEachRemaining(headerName -> System.out.println(headerName + ":
" + request.getHeader(headerName)));
원하는 정보만
request.getHeader("host");
header 모든 정보
Host 편의 조회
request.getServerName() = localhost
request.getServerPort() = 8080
Accept-Language
locale = ko
locale = en_US
locale = en
locale = ko_KR
request.getLocale() = ko
cookie
Cookie cookie = request.getCookies()
cookie.getName()
cookie.getValue()
Content
request.getContentType() = null
request.getContentLength() = -1
request.getCharacterEncoding() = UTF-8
HttpServletResponse 기능
응답 메시지 생성
- HTTP 응답코드 지정
편의 기능 제공
- Content-Type, cookie, Redirect
Status-line 응답코드
response.setStatus(HttpServletResponse.SC_OK);
응답코드가 상수로 정의되어 있음
response-header 직접 셋팅
response.setHeader("Content-Type", "text/plain;charset=utf-8");
message body
PrintWriter writer = response.getWriter();
writer.println("ok");
편의 메서드
Header
setContentType()
setCharacterEncoding()
Cookie
Cookie cookie = new Cookie("myCookie", "good");
cookie.setMaxAge(600); //600초
response.addCookie(cookie);
redirect
sendRedirect()
1)
Status Code 302
Location: /basic/hello-form.html
2)
response.setStatus(HttpServletResponse.SC_FOUND); //302
response.setHeader("Location", "/basic/hello-form.html");
3)
response.sendRedirect("/basic/hello-form.html");
writer.println("");
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>");
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);