티스토리 뷰
해당 글은 김영한님의 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의를 수강하고 정리한 게시글입니다.
서블릿 실습 환경 설정
스프링 부트 환경에서 서블릿을 등록하고 사용해보자.
참고:
서블릿은 톰캣 같은 웹 애플리케이션 서버를 직접 설치하고,그 위에 서블릿 코드를 클래스 파일로 빌드해서 올린 다음, 톰캣 서버를 실행하면 된다. 하지만 이 과정은 매우 번거롭다. 스프링 부트는 톰캣 서버를 내장하고 있으므로, 톰캣 서버 설치 없이 편리하게 서블릿 코드를 실행할 수 있다.
스프링 부트는 서블릿을 직접 등록해서 사용할 수 있도록 @ServletComponentScan
을 지원한다.
Application 파일에 이 어노테이션을 추가해주자.
[ServletApplication]
@ServletComponentScan // 서블릿 자동 등록
@SpringBootApplication
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
이제 간단한 서블릿 코드를 만들어 보고 알아보자.
[HelloServlet.java]
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("HelloServlet.service");
System.out.println("request = " + request);
System.out.println("response = " + response);
String username = request.getParameter("username");
System.out.println("username = " + username);
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().write("Hello " + username); // Http 메시지 바디에 값 쓰는 방법
}
}
서블릿을 만들기 위해 기본적으로 HttpServlet을 상속 받고 @WebServlet
서블릿 어노테이션으로 “name”으로 서블릿 이름, “urlPatterns”로 URL 매핑을 해준다.
HTTP 요청을 통해 매핑된 URL이 호출되면 서블릿 컨테이너는 service라는 메서드를 호출하게 된다.(오버라이드할 때 protected로 된 service를 오버라이드 할 것!)
그 후 request와 response등을 테스트 해보자.(자세한 내용은 뒤에 다룰 예정.)
HTTP 요청 메시지 로그로 확인하기
application.properties 파일에 다음을 추가해주자.
logging.level.org.apache.coyote.http11=debug
위를 적용하면 다음 그림같이 서버가 받은 HTTP 요청 메시지 로그를 출력하는 걸 알 수 있다.
[적용 예시]
참고:
운영서버에서 성능저하가 발생할 수 있으니 개발 단계에서만 사용하자.
'Backend > Spring' 카테고리의 다른 글
[Spring MVC] 07. HTTP 응답 데이터 실습 (0) | 2022.03.12 |
---|---|
[Spring MVC] 06. HTTP 요청 데이터 실습 (0) | 2022.03.11 |
[Spring MVC] 04. HTML, HTTP API, CSR, SSR (0) | 2022.03.08 |
[Spring MVC] 03. 동시 요청 - 멀티 쓰레드 (0) | 2022.03.07 |
[Spring MVC] 02. 서블릿(Servlet) (0) | 2022.03.06 |