如何从 HttpServletRequest 中仅获取部分 URL?

问题描述 投票:0回答:6

从以下网址我需要单独获取

(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

有人可以帮我解决这个问题吗?

java string url servlets httprequest
6个回答
40
投票

你说你想得到确切的:

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
,即您希望您的路径 include scheme

但是如果你不需要方案,快速的方法是:

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

你会得到(在你的情况下):

localhost:9090/dts


18
投票

据我所知,没有API提供方法,需要定制。

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

//试试这个

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

18
投票

只需从 URL 中删除 URI,然后向其附加上下文路径。无需摆弄松散的方案和端口,当您处理根本不需要出现在 URL 中的默认端口时,这只会更加乏味。


80

另请参阅:

    在调用转发到 JSP 的 Servlet 时,浏览器无法访问/查找 CSS、图像和链接等相关资源
  • (对于构成基本 URL 的 JSP/JSTL 变体)

3
投票

StringBuffer url = request.getRequestURL(); String uri = request.getRequestURI(); String ctx = request.getContextPath(); String base = url.substring(0, url.length() - uri.length() + ctx.length()); // ...



1
投票
端点

中获取针对端点的首页的URL的人。你可以用这个: String domain = request.getRequestURL().toString(); String cpath = request.getContextPath().toString(); String tString = domain.subString(0, domain.indexOf(cpath)); tString = tString + cpath;



0
投票

request.getHeader("referer")

此方法将返回您想要的内容,仅当当前请求中存在端口号时。在你的情况下它将返回:http://localhost:9090/dts

© www.soinside.com 2019 - 2024. All rights reserved.