서블릿 과정 대략적인 과정 설명
package hello.servlet.basic;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
HTTP 요청,응답 메세지가 어떤 과정으로 이루어지는지
전 글에서 정리했지만 서블릿과정에 대해 대략적으로 다시 설명을 먼저 해보자면
1. 내가 HTTP 요청을 WAS(Web Application Server)에게 보낸다.
2. WAS는 요청과 응답에 대한 HttpServletRequest와 HttpServletResponse 객체를 생성한다
3. 요청된 URL( http://localhost:8080/hello )에 매핑된 서블릿을 찾기 위해 서블릿 컨테이너에서 찾는다.
4. 해당 서블릿이 발견되면, 해당 서블릿의 service() 메서드가 호출한다.
5. HelloServlet의 service() 메서드가 실행한다.
service() 메서드는 HTTP 요청을 처리하는 핵심 메서드이다. 여기에서 요청을 처리하고 응답을 생성하는 코드를 작성해보자
1. HTTP 요청
서블릿 클래스
String username = request.getParameter("username");
package hello.servlet.basic;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println("username = " + username);
}
}
** 참고로 @WebServlet 서블릿 어노테이션에서 name, urlPatterns 은 중복이 있으면 안된다
request.getParameter() 를 통해 username을 조회할 수 있다
실행 후 URL 에 http://localhost:8080/hello?username=choi 검색해보기
쿼리 파라미터 란?
http://localhost:8080/hello?username=choi
이 부분을 쿼리 파라미터 라고 하는데 서블릿은 쿼리 파라미터를 쉽게 조회할 수 있다.
콘솔 실행결과 System.out.println("username = " + username);
2. HTTP 응답
응답 http 는 HttpServletResponse 객체에 넣어야한다
package hello.servlet.basic;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println("username = " + username);
//setContentType,setCharacterEncoding 는 헤더 정보에 들어간다
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
//write()는 http메세지 바디에 데이터가 들어간다
response.getWriter().write("hello " + username);
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().write("hello " + username);
http://localhost:8080/hello?username=choi 쳐보면 내가 보낸 응답 데이터가 보인다
개발자 모드(F12) 로 보면 ContentType 정보가 나와있음
* Content-Length 는웹 애플리케이션 서버가 자동으로 생성해준다.
welcome 페이지 만들기
- index.html
- basic.html
사용자가 애플리케이션에 처음 접속했을 때 보여지는 페이지
예를들어 사용자가 애플리케이션의 URL을 입력했을 때 특정한 페이지로 검색하지 않는 이상 기본적으로 보여지는 페이지이다.
> main/webapp/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li><a href="basic.html">서블릿 basic</a></li>
</ul>
</body>
</html
http://localhost:8080/index.html 검색했을때 나오는 index.html 페이지 화면
> main/webapp/basic.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li>hello 서블릿
<ul>
<li><a href="/hello?username=servlet">hello 서블릿 호출</a></li>
</ul>
</li>
<li>HttpServletRequest
<ul>
<li><a href="/request-header">기본 사용법, Header 조회</a></li>
<li>HTTP 요청 메시지 바디 조회
<ul>
<li><a href="/request-param?username=hello&age=20">GET - 쿼리
파라미터</a></li>
<li><a href="/basic/hello-form.html">POST - HTML Form</a></
li>
<li>HTTP API - MessageBody -> Postman 테스트</li>
</ul>
</li>
</ul>
</li>
<li>HttpServletResponse
<ul>
<li><a href="/response-header">기본 사용법, Header 조회</a></li>
<li>HTTP 응답 메시지 바디 조회
<ul>
<li><a href="/response-html">HTML 응답</a></li>
<li><a href="/response-json">HTTP API JSON 응답</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</body>
</html>
http://localhost:8080/basic.html 검색했을때 나오는 basic.html 페이지 화면
'공부' 카테고리의 다른 글
Spring MVC | HTTP, 웹서버와 WAS, 서블릿 특징, 서블릿 클래스 생성해보기 (0) | 2024.02.15 |
---|---|
Spring MVC | 스프링 부트 3.x 프로젝트 생성과 실행, 환경설정 (0) | 2024.02.13 |
Spring | 싱글톤 컨테이너 , @Configuration (0) | 2024.01.09 |
Spring | 싱글톤 패턴 적용하기, static, 싱글톤 문제점 (0) | 2024.01.08 |
Spring | 관심사의 분리 (AppConfig)와 의존성 주입 , AppConfig 리팩터링 (0) | 2023.12.19 |