서블릿 등록
- @WebServlet 서블릿 어노테이션
- name : 서블릿 이름
- urlPatterns : URL 매핑
@WebServlet(name = "hello", urlPatterns = "/hello")
public class Hello extend HttpServlet {
}
HTTP 요청 메시지 로그 properties
logging.level.org.apache.coyote.http11=debug
WAS의 요청 응답 구조
HttpServletRequest
- 개발자가 HTTP 요청 메시지를 편리하게 사용할 수 있도록 HTTP 요청 메시지를 파싱한 것을 담는 객체
- HTTP 요청 메시지를 편리하게 조회 할 수 있게 해줌
- 임시 저장소 기능
- 저장 : request.setAttribute(name, value)
- 조회 : request.getAttribute(name)
- 세션 관리 기능
- request.getSession()
기본 사용법
REQUEST-LINE
System.out.println("--- REQUEST-LINE - start ---");
/**
request.getMethod() = GET
request.getProtocol() = HTTP/1.1
request.getScheme() = http
request.getRequestURL() = http://localhost:8080/request-header
request.getRequestURI() = /request-header
request.getQueryString() = username=hello
request.isSecure() = false
**/
Headers
System.out.println("--- Headers - start ---");
request.getHeaderNames().asIterator()
.forEachRemaining(
headerName -> System.out.println(headerName + ": "
+ request.getHeader(headerName))
);
host: localhost:8080
connection: keep-alive
cache-control: max-age=0
sec-ch-ua: "Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_0) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/
webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site: none
sec-fetch-mode: navigate
sec-fetch-user: ?1
sec-fetch-dest: document
accept-encoding: gzip, deflate, br
accept-language: ko,en-US;q=0.9,en;q=0.8,ko-KR;q=0.7
Headers 편의 조회
[Host 편의 조회]
request.getServerName() = localhost
request.getServerPort() = 8080
[Accept-Language 편의 조회]
request.getLocales().asIterator()
.forEachRemaining(locale -> System.out.println("locale = " +locale));
locale = ko
locale = en_US
locale = en
locale = ko_KR
request.getLocale() = ko
[cookie 편의 조회]
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
System.out.println(cookie.getName() + ": " + cookie.getValue());
}
}
[Content 편의 조회]
request.getContentType() = null
request.getContentLength() = -1
request.getCharacterEncoding() = UTF-8
기타 정보
[Remote 정보]
request.getRemoteHost() = 0:0:0:0:0:0:0:1
request.getRemoteAddr() = 0:0:0:0:0:0:0:1
request.getRemotePort() = 54305
[Local 정보]
request.getLocalName() = localhost
request.getLocalAddr() = 0:0:0:0:0:0:0:1
request.getLocalPort() = 8080
HTTP 요청 데이터
- GET - 쿼리 파라미터
- /url**?username=hello
- 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
- 검색, 필터, 페이징...
- POST - HTML Form
- content-type: application/x-www-form-urlencoded
- 메시지 바디에 쿼리 파라미터 형식으로 전달
- 회원가입, 상품 주문...
- HTTP message body에 데이터를 직접 담아서 요청
- HTTP API에서 주로 사용
- JSON, XML, TEXT
- 데이터 형식은 주로 JSON 사용
- POST, PUT, PATCH
GET 쿼리 파라미터
[전체 파라미터 조회]
request.getParameterNames(paramName);
username=hello
age=20
[단일 파라미터 조회]
request.getParameter(username) = hello
request.getParameter(age) = 20
[이름이 같은 복수 파라미터 조회]
request.getParameterValues(username)
username=hello
API 메시지 바디 - JSON
JSON 형식 전송
- POST http://localhost:8080/request-body-json
- content-type: application/json
- message body: {"username": "hello", "age": 20}
- 결과: messageBody = {"username": "hello", "age": 20}
JSON 형식 파싱 추가
@Getter @Setter
public class HelloData {
private String username;
private int age;
}
private ObjectMapper objectMapper = new ObjectMapper();
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println("messageBody = " + messageBody);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
HttpServletResponse
- HTTP 응답 메시지 생성
- HTTP 응답 코드 지정
- 헤더 생성
- 바디 생성
- 편의 기능 제공
- Content-Type, 쿠키, Redirect
API JSON
HelloData data = new HelloData();
data.setUsername("kim");
data.setAge(20);
//{"username":"kim","age":20}
String result = objectMapper.writeValueAsString(data);
response.getWriter().write(result);
'Spring > MVC' 카테고리의 다른 글
[MVC] 요청 매핑 (0) | 2024.09.10 |
---|---|
[MVC] MVC 구조 (0) | 2024.09.06 |
[MVC] 프론트 컨트롤러 패턴 (0) | 2024.09.05 |
[MVC] MVC 패턴 (0) | 2024.09.05 |