9

If a single servlet serves data from two domains example1.com and example2.com, how do you retrieve the domain information from the request in a Java servlet?

The purpose is to perform different actions depending on the domain.

Bacon
  • 91
  • 1
  • 1
  • 2

1 Answers1

14

Very easy, javax.servlet.ServletRequest.getServerName(). It also provides further methods to retrieve request information, getScheme(), getServerPort()...

Edit: If you have a web server guarding your application server, it must be configured to support this, otherwise getServerName() returns the name of your application server which may not be what you want...

home
  • 12,468
  • 5
  • 46
  • 54
  • 3
    This is wrong, getServerName: Returns the host name of the server to which the request was sent. It is the value of the part before ":" in the Host header value, if any, or the resolved server name, or the server IP address. To get the domain from te client request, do: String domain = new URL(request.getRequestURL().toString()).getHost(); – Nizar B. Apr 18 '16 at 13:51
  • OncePerRequestFilter eg: https://www.baeldung.com/spring-onceperrequestfilter then in that request :String domain = new URL(request.getRequestURL().toString()).getHost(); to get the domain of the request and match it with valid domain names and reject or accept request based on that – satyesht Jan 19 '23 at 21:10