4

In Java EE, how can I dynamically retrieve the full URL for my application?

For example, if the URL is "localhost:8080/myapplication/", I would like a method that can simply return this to me, either as a String or something else.

I am running GlassFish as application server.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
csvan
  • 8,782
  • 12
  • 48
  • 91

2 Answers2

7

Inside any servlet or filter you have access to HttpServletRequest which allows you to see what URL was used by the client to access your application, e.g. try HttpServletRequest.getRequestURL().

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

In JSF I was able to achieve this relatively easily using the following helper function (all you need is a reference to the HttpServletRequest:

public static String getRequestUrl() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    StringBuffer requestURL = request.getRequestURL();
    if (request.getQueryString() != null) {
        requestURL.append("?");
        requestURL.append(request.getQueryString());
    }
    return requestURL.toString();
}
Marco
  • 73
  • 8