JSP或JavaScript等效于PHP的$ _SERVER [“HTTP_HOST”]?

时间:2009-04-22 21:51:49

标签: java php javascript url window.location

我在我的JavaScript中使用了一个绝对URL,我为window.location编写了硬编码。

我不想每次测试我的应用时都要更改它。在PHP中,我会通过测试$ _SERVER [“HTTP_HOST”]变量来找出我所在的服务器并进行相应调整。但是,我对Java并不熟悉,并且想知道它是否有类似的方法?或者甚至可能是JavaScript有类似的方法?

代码如下:

var url = "http://172.17.1.107/store/results/index.jsp";
window.location = url;

我想做的是:

var server = [something that returns just 172.17.1.107 (with or without the http:// is fine)]
var url = "http://" + server + "/store/results/index.jsp";
window.location = url;

在PHP中我会这样做:

var server = <?= $_SERVER["HTTP_HOST"] ?>
var url = "http://" + server + "/store/results/index.php";
window.location = url;

有什么想法吗?我想我的运作是假设您必须使用绝对URL来更改JavaScript中当前窗口的位置。如果还有其他方法可以在没有绝对URL的情况下更改JavaScript中的窗口位置,请随时提供。

提前致谢...

4 个答案:

答案 0 :(得分:7)

您需要的是:

request.getServerName()

一个例子:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

答案 1 :(得分:4)

位置对象has several properties,以及您想要的位置对象hostname

或者,您可以选择使用根相对网址,只需设置pathname属性,而不是干扰主机业务!

location.pathname = "/store/results/index.jsp";

答案 2 :(得分:3)

使用Javascript:

var server = window.location.hostname;

答案 3 :(得分:0)

你真的应该搜索这个,但在JSP中它是:

request.getRemoteHost()
相关问题