45

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.

0

5 Answers 5

61
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)
2
  • This doesn't work anymore. I'm still finding out how to do it now. Aug 16, 2016 at 7:00
  • 2
    These methods simply use the value of the Host header from the request, which isn't always safe to use, since it can be altered by anyone, including any proxies between the client and server. So for example, if your Tomcat instance is behind an Apache server, these methods will likely return a localhost address (see the comments on this answer)
    – typeracer
    Mar 27, 2020 at 23:02
16

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());
}
1
  • 1
    To get an url: request.getServerName() + ":" + request.getServerPort(); Oct 26, 2014 at 9:12
8

@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
4

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

0
3

I have found in my old project the string:

request.getHeader("host").contains("xxx")

maybe it is the solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.