JSP or JavaScript equivalent to PHP's $_SERVER["HTTP_HOST"]?
Asked Answered
K

4

7

I've go an absolute URL in my JavaScript that I have hard coded for window.location.

I don't want to have to change this every time I am testing my app. In PHP I would have handled this by testing the $_SERVER["HTTP_HOST"] variable to find out what server I am on, and adjust accordingly. However, I'm not as familiar with Java and am wondering if it has a similar method? Or if maybe even JavaScript had a similar method?

The code is as follows:

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

What I would like to do is:

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;

In PHP I would have just done this:

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

Any ideas? I suppose I'm operating under the assumption that you have to do an absolute URL to change the location of the current window in JavaScript. If there is another way to change the window location in JavaScript without an absolute URL, please feel free to offer that as well.

Thanks in advance...

Kaylee answered 22/4, 2009 at 21:51 Comment(0)
H
8

What you need is:

request.getServerName()

An example:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Hamitic answered 22/4, 2009 at 22:7 Comment(0)
C
6

Javascript:

var server = window.location.hostname;
Cogent answered 22/4, 2009 at 21:59 Comment(0)
G
4

The location object has several properties, and the one you'd want is hostname.

Or, you can optionally just use a root-relative URL and just set the pathname property and not mess with the host business at all!

location.pathname = "/store/results/index.jsp";
Graphics answered 22/4, 2009 at 22:1 Comment(0)
J
0

You really should have search for this but in JSP it's :

request.getRemoteHost()
Jaquith answered 22/4, 2009 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.