김영한 [스프링 MVC 1편] - 강의정리
HttpServletRequest - 개요
HttpServletRequest 역할
HTTP 요청 메시지를 개발자가 직접 파싱해도 되지만, 매우 불편하다.
서블릿은 개발자가 HTTP 요청메시지를 편리하게 사용할 수 있도록 개발자 대신 HTTP 요청을 파싱한다.
그 결과를 HTTPServletRequest 객체에 담아 제공한다.
HTTP 요청 메시지
POST /save HTTP/1.1
Host: localhost:8080
Content-Type: application/~
username=kim&age=20
- START LINE
- HTTP 메소드
- URL
- 쿼리 스트링
- 스키마, 프로토콜
- 헤더
- 헤더조회
- 바디
- form 파라미터 형식 조회
- message body 데이터 직접 조회
- 임시 저장소 기능
- 해당 HTTP 요청이 시작부터 끝날때 까지 유지되는 임시 저장소 기능
- 저장 : request.setAttribute(name, value);
- 조회 : request.getAttribute(name, value);
- 세션 관리 기능
- request.getSession(create: true);
HttpServletRequest, HttpServletResponse를 사용할 때 가장 중요한 것은
이 객체들이 HTTP 요청 메시지, 응답 메시지를 편리하게 사용하도록 도와주는 객체라는 점이다.
따라서 기능에 대해 깊이있는 이해를 하려면, HTTP 스펙이 제공하는 요청, 응답 메시지 자체를 이해해야한다.
HttpServletRequest - 기본사용법
//http://localhost:8080/request-header?username=hello
@WebServlet(name = "requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHeaderServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
printStartLine(request);
printHeaders(request);
printHeaderUtils(request);
printEtc(request);
response.getWriter().write("ok");
}
}
- HTTP 메시지의 start-line, header 정보 조회 방법
HTTP 요청 데이터 - 개요
- HTTP 요청 메시지를 통해 클라이언트에서 서버로 데이터를 전달한다.
주로 3가지 방법이 있다.
- GET - 쿼리 파라미터
- POST - HTML Form
- HTTP message body에 데이터를 직접 담아서 요청
HTTP 요청 데이터 - GET 쿼리 파라키터