如何在 undertow 中获取 HttpServletRequest 或 HttpServletResponse



我用undertow开发了一个web,但我不知道如何在路由中获取HttpServletRequest和HttpServletResponse。我不想使用 HttpServerExchange 对象。

我尝试使用

HttpServletRequest request = (HttpServletRequest) exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletRequest();

以获取请求,但失败了。

public class HelloServer {
  private static HttpHandler handler = new RoutingHandler()
      .get("/", HelloServer::doGet);
  private static void doGet(HttpServerExchange exchange) {
    ServletRequestContext attachment = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    System.out.println(attachment); // attachment: null
    exchange.getResponseSender().send("hello world");
  }
  public static void main(String[] args) {
    Undertow undertow = Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler(handler)
        .build();
    undertow.start();
  }
}

有没有办法获取HttpServletRequest和HttpServletResponse对象?

你可以试试这个:

ServletRequestContext.current().getServletRequest()

相关内容

  • 没有找到相关文章

最新更新