Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从HttpServletRequest提取上下文路径和其他URL信息_Java_Url_Servlets - Fatal编程技术网

Java 从HttpServletRequest提取上下文路径和其他URL信息

Java 从HttpServletRequest提取上下文路径和其他URL信息,java,url,servlets,Java,Url,Servlets,我正在本地主机端口8080上运行我的应用程序。基本url是: 现在从HttpServletRequest如何提取该部分 目前我正在这样做: String schema = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); String pa

我正在本地主机端口8080上运行我的应用程序。基本url是:

现在从
HttpServletRequest
如何提取该部分

目前我正在这样做:

String schema = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
String path = schema + "://" + serverName + ":" + serverPort + contextPath;
System.out.println(path);
这里的request是
HttpServletRequest
的实例

这个程序对吗

有没有其他方法来获取信息

如果我托管我的应用程序并说URL是。。。那么上述程序代码是否有效


我发现的另一个方法是:

String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());

在我需要的地方:

HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest();
String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());          
submitLink.add(new WebMarkupContainer("submitImage").add(new AttributeModifier("src", path + "/ASSETS/css/images/login-btn.png")));

我正在开发一个Wicket应用程序,其中需要指定
的src,这两种方法都可以,但我更喜欢第一种。没有比这更直接的了,尽管如果您解释了为什么需要这个值,可能会有。

谢谢。我已经更新了我的答案来解释这个场景。你能告诉我为什么喜欢第一个吗?我更喜欢第一个,因为第二个将在根上下文中中断,其中上下文路径是零长度字符串。考虑到您正在做的事情,您可能可以进行一些优化,以避免多次执行相同的操作,但在Servlet API中没有任何有用的东西。