java - Grizzly 的 Request.getPathInfo 总是返回 null?

标签 java http grizzly

我正在尝试实现自定义 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 的“未路由”部分?

最佳答案

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

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

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

结果将是:

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

关于java - Grizzly 的 Request.getPathInfo 总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18963562/

相关文章:

java - jersey-test-framework grizzly 返回 404 未找到错误

java - @Post 方法在 @Path 中捕获括号在 Jersey 中不匹配

java - ByteBuffer翻转方法的目的是什么? (为什么它被称为 "flip"?)

Java MVC 项目——要么我不能更新绘图,要么我看不到它

java - 谁能推荐现成的 ACL Java 库?

带有 Apache HttpClient 的 Java 客户端连接到 Druid

eclipse - grizzly 记录到 stderr,在 eclipse 中很烦人

java - 如何通过执行 Prepared Statement 获取 boolean 值?

http - 我如何处理 HTTP GET 查询字符串长度限制并仍然想成为 RESTful?

http - URL 应该使用什么字符编码?