如何从HttpServletRequest只获取部分URL?
从以下URL我需要单独获取(http://localhost:9090/dts)
。
那是我需要删除(documents/savedoc)
(OR)
需要得到 – (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
任何人都可以帮我解决这个问题吗?
AFAIK对此没有API提供的方法,需要定制。
String serverName = request.getServerName(); int portNumber = request.getServerPort(); String contextPath = request.getContextPath();
// 试试这个
System.out.println(serverName + ":" +portNumber + contextPath );
你说你想准确得到:
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
当然还有其他变种,就像其他已经写过的……
这是你原来的问题,你询问如何获得http://localhost:9090/dts
,即你希望你的路径包括方案。
如果您仍然不需要方案,快速方法是:
String resultPath = request.getHeader("Host") + request.getContextPath();
你会得到(在你的情况下): localhost:9090/dts
只需从URL中删除URI,然后将上下文路径附加到它。 无需摆弄松散的方案和端口,当您处理默认端口80
,这些方案和端口根本不需要出现在URL中。
StringBuffer url = request.getRequestURL(); String uri = request.getRequestURI(); String ctx = request.getContextPath(); String base = url.substring(0, url.length() - uri.length() + ctx.length()); // ...
也可以看看:
- 在调用转发到JSP的Servlet时,浏览器无法访问/查找CSS,图像和链接等相关资源 (对于组成基本URL的JSP / JSTL变体)
根据我的理解,您只需要域部分和上下文路径。 基于这种理解,您可以使用此方法获取所需的字符串。
String domain = request.getRequestURL().toString(); String cpath = request.getContextPath().toString(); String tString = domain.subString(0, domain.indexOf(cpath)); tString = tString + cpath;