如何在undertow中获取HttpServletRequest或HttpServletResponse?

时间:2019-04-12 05:53:58

标签: undertow

我用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对象吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

ServletRequestContext.current().getServletRequest()