1. 개요
Undertow를 시작해보자. Undertow는 Java 애플리케이션 안에 내장해서 실행할 수 있는 가벼운 웹 서버다. 별도의 WAS를 설치하지 않고도 코드에서 HTTP 리스너와 핸들러를 직접 구성해 간단한 서버를 띄울 수 있다.
아래 예제는 Maven 프로젝트에 Undertow 의존성을 추가한 뒤, 8080 포트에서 문자열을 응답하는 가장 기본적인 서버를 실행하는 흐름이다.
2. Maven 프로젝트 생성
Maven 프로젝트를 생성한다. 이 과정은 IDE나 명령어 사용 방식에 따라 달라질 수 있으므로 자세한 설명은 생략한다.
3. pom.xml
pom.xml에 Undertow 관련 의존성을 추가한다. 단순한 HTTP 서버 예제만 실행한다면 핵심은 undertow-core이지만, 이후 Servlet이나 WebSocket 예제를 확장할 수 있도록 관련 모듈도 함께 추가해 둔다.
<dependency> <groupId>io.undertow</groupId> <artifactId>undertow-core</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-servlet</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-websockets-jsr</artifactId> <version>2.0.1.Final</version> </dependency>
4. 코드
다음은 localhost:8080으로 들어오는 요청에 대해 Hello sarc.io라는 텍스트를 응답하는 예제다.
package io.sarc.undertowTest;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
public class HelloWorldServer {
public static void main(String[] args) {
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(new HttpHandler() {
public void handleRequest(final HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello sarc.io");
}
})
.build();
server.start();
}
}
5. 실행 확인
HelloWorldServer의 main 메서드를 실행한 뒤 브라우저에서 다음 주소로 접속한다.
http://localhost:8080
정상적으로 실행되면 화면에 다음과 같은 응답이 표시된다.
Hello sarc.io
만약 서버가 시작되지 않는다면 8080 포트를 이미 다른 프로세스가 사용 중인지 확인한다. 필요하다면 addHttpListener(8080, "localhost")의 포트 번호를 다른 값으로 변경해 테스트할 수 있다.