我正在尝试实现自定义 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
。谁能给我解释一下:
- 为什么在此示例中
getHttpHandlerPath()
和getPathInfo()
都返回null
? - 另外,我怀疑后者是前者的结果,对吗?
- 如何在 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/