자바부터 스프링까지 - 서블릿

Roeniss Moon·2021년 5월 26일
0

자바

목록 보기
2/2

앞 글을 읽었다면 서블릿이 무엇인지 알 수 있을 것이다. 서블릿은 단지 Specification이며*, 이를 구현한 Application Server가 필요하다. 그리고 만만한 건 tomcat이다.

*구현체... 즉 servlet이 포함된 클래스파일들도 서블릿이라고 부르는 것 같긴 하다.

아래 내용은 tutorialspoint 튜토리얼 중 중간까지만 다루고있으며, 그 이후 내용은 눈으로만 훑어봐도 충분할 것 같다. 특히 Filter 부분을 보라. Spring에서 쓰는 필터와 똑같아 보인다!

서블릿 실습

macOS 기준이다.

톰캣 세팅

brew install tomcat@8
brew services start tomcat@8
brew info tomcat@8 # 톰캣 주소 확인하기

마침 내가 쓰는게 버전 8이라서 그냥 8로 고정했다.

톰캣 디렉토리까지 들어가야 하는데, macOS라면 /usr/local/Cellar/tomcat@8/$VERSION/libexec/정도까지 오면 된다.

여기까지 따라왔으면 http://localhost:8080/ 에서 누가봐도 톰캣으로밖에 생각할 수 없는 페이지가 나온다. 그리고 해당 파일은 webapps/ROOT/index.jsp에 존재한다. 그런데 webapps/ROOT/WEB-INF/web.xml이 ROOT 라는 application의 설정 파일인데, 해당 파일 안에 index.jsp와 관련된 내용이 전혀 없다.

대신 conf/web.xml 파일을 보면 제일 아래에 이런 내용이 있다. 아마 이게 영향을 준 거겠지.

// ...
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

서블릿 코드 작성

나중에 옮기기 힘드니 아예 자바 코드를 ROOT/WEB-INF/classes 아래에 만들면 된다. 여기가 지정된 위치다.

// HelloWorld.java

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
 
   private String message;

   public void init() throws ServletException {
      // Do required initialization
      message = "Hello World";
   }

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set response content type
      response.setContentType("text/html");

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
   }

   public void destroy() {
      // do nothing.
   }
}

이걸 바이트코드(.class)로 컴파일하면 되는데, 기본 jdk에는 servlet 패키지가 없다. 아래처럼 하자.

CLASSPATH=/usr/local/Cellar/tomcat@8/$VERSION/libexec/lib/servlet-api.jar:$CLASSPATH javac HelloWorld.java

/usr/local/Cellar/tomcat@8/$VERSION/libexec/webapps/ROOT/WEB-INF/classes/HelloWorld.class << 이러한 형태가 되도록 위치시키자.

이것이 흔히 말하는 하나의 서블릿이다. 이걸 /usr/local/Cellar/tomcat@8/$VERSION/libexec/webapps/ROOT/WEB-INF/web.xml에서 세팅해주자.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

  <servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>HelloWorld</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorld2</url-pattern>
  </servlet-mapping>

</web-app>

이후 톰캣을 재실행

brew services restart tomcat@8

그러면 http://localhost:8080/HelloWorld, http://localhost:8080/HelloWorld2 에 접속했을 때 모두 같은 화면을 보게 될 것이다.

추가로 확인해보면 좋은 것

톰캣을 재실행한 직후부터 브라우저에서 새로고침을 반복해보자. 정상적인 HelloWorld를 포함해서 총 세 개의 메시지를 볼 수 있다.

profile
기능이 아니라 버그예요

0개의 댓글