【问题标题】:Grizzly's Request.getPathInfo returns always null?Grizzly 的 Request.getPathInfo 总是返回 null?
【发布时间】:2013-09-23 15:49:02
【问题描述】:

我正在尝试实现自定义 Grizzly HttpHandler,但尝试简单地从传入请求中提取路径信息却失败了。请参阅下面的最小示例:

public class PathInfoTest {
    public static void main(String[] args) throws IOException {
        final HttpServer httpServer = new HttpServer();
        final NetworkListener nl = new NetworkListener(
                "grizzly", "localhost", 8080);
        httpServer.addListener(nl);
        httpServer.getServerConfiguration().addHttpHandler(
                new HandlerImpl(), "/test");   
        httpServer.start();
        System.in.read();
    }

    private static class HandlerImpl extends HttpHandler {
        @Override
        public void service(Request request, Response response)
                throws Exception {

            System.out.println(request.getPathInfo());
            System.out.println(request.getContextPath());
            System.out.println(request.getDecodedRequestURI());
            System.out.println(request.getHttpHandlerPath());
    }
}

我认为这会告诉 Grizzly,URL 以“/test”开头的所有传入请求都应该由HandlerImpl 处理,这似乎到目前为止有效。但是,当对 http://localhost:8080/test/foo 执行 GET 操作时,此代码会将以下内容打印到 stdout

null
/test
/test/foo
null

我主要关心的是第一个null,它应该是路径信息。在这个例子中,我希望它是foo,而不是null。谁能给我解释一下:

  1. 为什么在这个例子中getHttpHandlerPath()getPathInfo()都返回null
  2. 另外,我怀疑后者是前者的结果,对吗?
  3. 如何在 Grizzly 中获取 URL 的“未路由”部分?

【问题讨论】:

标签: java http grizzly


【解决方案1】:

您必须在映射中使用星号(类似于 Servlet)才能看到正确的 pathInfo 值。 例如,请使用以下映射:

httpServer.getServerConfiguration().addHttpHandler(
     new HandlerImpl(), "/test/myhandler/*");

并向http://localhost:8080/test/myhandler/foo/bar提出请求

结果将是:

/foo/bar
/test
/test/myhandler/foo/bar
/myhandler

【讨论】:

  • 非常感谢,这可以解决问题。这应该明确地成为文档的一部分。
  • 这个映射对应于 Servlet 映射,但我同意我们必须更好地记录 addHttpHandler() 方法以使其清楚。感谢您的反馈:)
猜你喜欢
  • 1970-01-01
  • 2014-03-04
  • 2016-11-02
  • 2014-05-06
  • 2012-06-05
  • 2014-05-30
  • 2014-02-23
  • 2017-10-12
  • 2013-08-16
相关资源
最近更新 更多