Search code examples
resteasyundertow

Use Undertwo web server to serve both static pages and web service


I am trying to use Undertow to serve both static pages and web service (RestEasy) but couldn't get both of them working the same time. I see others asking the same questions like HTTP Handler and Resteasy Deployment with undertow and resteasy. There has to be a way to get this work, right? WildFly can handle both on the same port. But how could I do this? Thanks!


Solution

  • How about:

    DeploymentInfo servletBuilder = deployment()
        .setClassLoader(App.class.getClassLoader())
        .setContextPath("/api")
        .setDeploymentName("test.war")
        .addServlets(
            servlet("MessageServlet", MessageServlet.class)
                .addInitParam("message", "Hello World")
                .addMapping("/*"),
            servlet("MyServlet", MessageServlet.class)
                .addInitParam("message", "MyServlet")
                .addMapping("/myservlet"));
    DeploymentManager manager = defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    HttpHandler servletHandler = manager.start();
    
    
    Undertow.builder().addHttpListener(8080, "0.0.0.0")
        .setHandler(Handlers.path()
    
            // REST API path
            .addPrefixPath("/servlet", servletHandler)
    
            // Serve all static files from a folder
            .addPrefixPath("/static", new ResourceHandler(
                new PathResourceManager(Paths.get("/path/to/www/"), 100))
                .setWelcomeFiles("index.html"))
    
        ).build().start();
    

    The servlet part is taken from Undertow's official examples, here. You can talk to your Message servlets via:

    GET /servlet/api

    POST /servlet/api/myservlet