Home Ask Login Register

Developers Planet

Your answer is one click away!

Adam Arold February 2016

Is there a way to use the Servlet API with Undertow?

I'm just discovering how Undertow works and I was surprised by its api:

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 World");

Is there a way to use the more convenient servlet api like this somehow?

Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(new HttpHandler() {
                    public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
                        // ...

What I'm trying to achieve is to replace the currently working Jetty container which uses the servlet api by Undertow but after reading the docs and the source I can't seem to find a way to do so. I'm not using .war files just an embedded Jetty. Do someone has any pointers?


BalusC February 2016

It's documented in section Creating a Servlet Deployment. Here's a MCVE based on the documentation provided that you've the dependencies right, along with the Servlet API.

package com.stackoverflow.q35269763;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test {

    public static void main(String... args) throws Exception {
        DeploymentInfo servletBuilder = Servlets.deployment().setClassLoader(Test.class.getClassLoader())
                new HttpServlet() {
                    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                        response.getWriter().write("Hello World!");
        DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
        PathHandler path = Handlers.path(Handlers.redirect("/myapp")).addPrefixPath("/myapp", manager.start());
        Undertow server = Undertow.builder().addHttpListener(8888, "localhost").setHandler(path).build();


When you open http://localhost:88

Post Status

Asked in February 2016
Viewed 3,966 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life