有没有办法将 Servlet API 与 Undertow 一起使用



我只是在发现Undertow是如何工作的,我对它的api感到惊讶:

Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                        exchange.getResponseSender().send("Hello World");
                    }
                }).build();
        server.start();

有没有办法以某种方式使用更方便的servlet api

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

我试图实现的是替换当前工作的 Jetty 容器,该容器使用 Undertow 的 servlet api,但在阅读文档和源代码后,我似乎找不到这样做的方法。我不是在使用.war文件,而只是一个嵌入式码头。有人有什么指示吗?

它记录在创建 Servlet 部署一节中。这是一个基于文档的 MCVE,前提是您拥有正确的依赖项以及 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())
            .setDeploymentName("myapp").setContextPath("/myapp")
            .addServlets(Servlets.servlet("myservlet",
                new HttpServlet() {
                    @Override
                    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                        response.getWriter().write("Hello World!");
                    }
                }.getClass()).addMapping("/myservlet"));
        DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
        manager.deploy();
        PathHandler path = Handlers.path(Handlers.redirect("/myapp")).addPrefixPath("/myapp", manager.start());
        Undertow server = Undertow.builder().addHttpListener(8888, "localhost").setHandler(path).build();
        server.start();
    }
}

当您在复制粘贴运行上述代码后在自己喜欢的网络浏览器中打开 http://localhost:8888/myapp/myservlet 时,您将看到

世界您好!

相关内容

  • 没有找到相关文章

最新更新