I am trying to get the domain name from the url with JSTL. The 2 methods I know return the wrong information. I need exactly what is in the URL.
When I do:
${pageContext.request.remoteHost}
I get my server's IP.
When I do:
${pageContext.request.serverName}
I normally get the right domain name, but on a server we have on amazon its returning "server1" instead of the correct domain name, probably because of the way it handles multiple domains.
Anyone know how I can get the current domain name in the URL?
I may need to get the URL and then parse it. How would I do that?
You should be using ServletRequest#getLocalName() instead. It returns the real hostname of the server. The ServletRequest#getServerName() indeed returns the value as set in Host header.
${pageContext.request.localName}
That's all. The solutions suggested in other answers are plain clumsy and hacky.
By the way, the ServletRequest#getRemoteHost() doesn't return the server's hostname, but the client's one (or the IP when the hostname is not immediately resolveable). It's obviously the same as the server's one whenever you run both the webserver and webbrowser at physically the same machine. If you're interested in the server's IP, use ServletRequest#getLocalAddr(). The terms "local" and "remote" must be interpreted from server's perspective, not from the client's. It's after all the server there where all that Java code runs.
You can parse domain name from URL
OR
public static String getDomainName(String url)
{
URL u;
try {
u = new URL(url);
}
catch (Exception e) {
return "";
}
return u.getHost();
}
You can use HttpServletRequest.getRequestUrl() to:
Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.
this would return a String like Get domain name in url with JSTL?
It should then be trivial to parse this to find the string that comes after the scheme (http, https, etc) and before the requestURI.
${pageContext.request.contextPath}
Related
My problem
In my android application I get url input from user, like "www.google.com".
I want to find out for the given url whether to use http or https.
What I have tried
after referring to some Stack Overflow questions I tried with getScheme()
try {
String url_name="www.google.com";
URI MyUri = new URI(url_name);
String http_or_https="";
http_or_https=MyUri.getScheme();
url_name=http_or_https+"://"+urlname;
Log.d("URLNAME",url_name);
}
catch (Exception e) {
e.printStackTrace();
}
But my above code throws an exception.
My question
Is above approach getScheme() correct or not?
If above approach is incorrect, how to find url http or https?
A domain name is a domain name, it has nothing to do with protocol. The domain is the WHERE, the protocol is the HOW.
The domain is the location you want to go, the protocol is how do you go there, by bus, by plane, by train or by boat. It makes no sense to ask 'I want to go to the store, how do I ask the store if I should go by train or by car?'
The reason this works in browsers is that the browser usually tries to connect using both http and https if no protocol is supplied.
If you know the URL, do this:
public void decideProtocol(URL url) throws IOException {
if ("https".equals(url.getProtocol())) {
// It is https
} else if ("http".equals(url.getProtocol())) {
// It is http
}
}
You can check, the given url is http or https by using URLUtils.
URLUtil.isHttpUrl(String url); returns True if the url is an http.
URLUtil.isHttpsUrl(String url); returns True if the url is an https.
You could use the Apache UrlValidator.
You can specify the allowed url schema and in your case the code look something like this:
String[] schema = {"https"};
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("http://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
if (urlValidator.isValid("https://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
A hierarchical URI is subject to further parsing according to the syntax
[scheme:][//authority][path][?query][#fragment]
so your url_name lack of scheme.
if url_name is "https://www.google.com", so the scheme is https.
refer: http://docs.oracle.com/javase/7/docs/api/java/net/URI.html
You can't get it from just URL. It doesn't make sense. Some websites can work with both http & https. It depends upon website itself whether they use SSL certificate or not.
As was pointed out, if a user didn't dare to provide full url including protocol type. The app might use kind of trial and error approach, try to establish connection using the list of available protocols. (http, https). The successful hit might be considered as a default. Again, all this about usability,this method is better than just annoying an inattentive user with ugly error message.
ranjith- I will store some sort of mapping between URI (main domain) and preferred protcol within application..can have pre-defined mappings based on what you know and then let that mapping grow as more Uris added..
I have a java.net.URL object in a Spring 4 #RestController. How can I check if the URL (HTTP) leads to the current machine (this Spring application) or is an URL to an external HTTP-Source?
I found out that java.net.URL does hostname resolution to compare to other URL object. Is there a way to reuse this resolution to not having to reinvent the wheel?
Using the code from this post you can check if it is a local IP. You should pass an InetAddress object, so get it from your URL using the following command:
InetAddress.getByName(new URL(urlString).getHost());
I think you can use InetAddress class to check this.
1.First get the local system IP address
String localAddress = InetAddress.getLocalHost().getHostAddress();
2.Fetch the address of url that you want to match.
String requestAddress = InetAddress.getByName(new URL(url).getHost()).getHostAddress();
Now you can compare both 1 and 2 address string.
I hope it helps!!!
I want to validate the website address user input in java side. I have used org.apache.commons.validator.routines.UrlValidator for this, but it needs URLs to start with http://, https://, or ftp://.
However, in my case i want to accept the address just starting with www., like www.stackoverflow.com. How can I do this?
Create an URI object and check if getScheme() is empty or null. If so, preprend "http://"
I'm working on project using Java, in which IP address will be identity of the client/user. So I'm facing one problem: where user can spoof their host identity, that can lead to false identity of the user. So, anyone know, how to detect whether the host is using proxy or not?
InetAddress thisIp = InetAddress.getLocalHost();
I'm using above code to detect the host IP address.
You cannot 100% reliably check this, but to cover the most proxies, you could check the presence of the X-Forwarded-For request header.
if (request.getHeader("X-Forwarded-For") != null) {
// Client is likely using a proxy.
}
There is no standard for this. Each proxy may have its own specific set of additional/custom headers. You could log the retrieved request headers and examine which headers are been set by certain proxies and then alter the code accordingly. Again, you cannot reliably check this. Some proxies may even have no additional headers at all. You'd need to maintain a list of IP addresses of "well known" proxies so that you can check getRemoteAddr() against it.
Unrelated to the concrete problem, as you tagged this with jsp, I would only add that writing Java code inside a JSP is a poor practice. You'd normally do this in a normal Java class like a servlet or a filter.
I thought ServletContext might provide a method. Does the getAttribute() method of ServletContext provide any help i.e. is there an attribute name (maybe "host", "port") that will be of help.
The reason for this is I want my application to run wherever it is deployed, and at one point I have to allow a user to click a link that points to a location on the file server. Hence I need to reference by the host and port and cannot use an internal reference.
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)
The ServletRequest object that has been passed to your doGet, or doPost method has getServerName and getServerPort methods that provide this information.
eg
public void doGet(ServletRequest request, ServletResponse response) {
System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());
}
#Everyone has a good answer. But taking scheme, server name and port then mergin them. There is a simpler way:
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String host = url.substring(0, url.indexOf(uri)); //result
As others mentioned above, host and port can be retrieved through request. On the other hand, it is impossible for the ServletContext provide the info since java applications are unaware of your host environment. i.e., an application with context path "foo"(which could be retrieved by ServletContext#getContextPath()) could receive requests both from a http port 8080 and a https port 8043. Reference: https://web.archive.org/web/20120401225136/http://www.java.net:80/node/701934
I have found in my old project the string:
request.getHeader("host").contains("xxx")
maybe it is the solution?