如何从 HttpServletRequest 获取 URL 的一部分?

新手上路,请多包涵

从以下 URL,我需要单独获取 (http://localhost:9090/dts)

那就是我需要删除 (documents/savedoc) (或)

只需要得到 - (http://localhost:9090/dts)

 http://localhost:9090/dts/documents/savedoc

是否有任何方法可用于获取上述信息?

我尝试了以下并得到了结果。但仍在努力。

 System.out.println("URL****************"+request.getRequestURL().toString());
System.out.println("URI****************"+request.getRequestURI().toString());
System.out.println("ContextPath****************"+request.getContextPath().toString());

URL****************http://localhost:9090/dts/documents/savedoc
URI****************/dts/documents/savedoc
ContextPath****************/dts

谁能帮我解决这个问题?

原文由 user1732653 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 774
2 个回答

AFAIK 对此没有 API 提供的方法,需要定制。

 String serverName = request.getServerName();
int portNumber = request.getServerPort();
String contextPath = request.getContextPath();

// 尝试这个

System.out.println(serverName + ":" +portNumber + contextPath );

原文由 NPKR 发布,翻译遵循 CC BY-SA 3.0 许可协议

你说你想得到:

 http://localhost:9090/dts

在您的情况下,上述字符串包括:

  1. 方案http
  2. 服务器 主机名localhost
  3. 服务器 端口9090
  4. 上下文路径dts

(有关请求路径元素的更多信息,请参阅官方 Oracle _Java EE 教程_: 从请求中获取信息

##第一个变体:###

 String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();  // includes leading forward slash

String resultPath = scheme + "://" + serverName + ":" + serverPort + contextPath;
System.out.println("Result path: " + resultPath);

##第二种变体:##

 String scheme = request.getScheme();
String host = request.getHeader("Host");        // includes server name and server port
String contextPath = request.getContextPath();  // includes leading forward slash

String resultPath = scheme + "://" + host + contextPath;
System.out.println("Result path: " + resultPath);


两种变体都会给你你想要的: http://localhost:9090/dts

当然还有其他变体,就像其他人已经写过的一样……

这只是在您最初的问题中,您询问了如何获取 http://localhost:9090/dts ,即您希望您的路径 包含 方案。

如果您仍然不需要方案,快速的方法是:

 String resultPath = request.getHeader("Host") + request.getContextPath();

你会得到(在你的情况下): localhost:9090/dts

原文由 informatik01 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题