Java HttpServletRequest get URL in browsers URL bar

If your current request is coming from an "inside the app-server" forward or include, the app-server is expected to preserve request information as request attributes. The specific attributes, and what they contain, depends on whether you're doing a forward or an include.

For <jsp:include>, the original parent URL will be returned by request.getRequestURL(), and information about the included page will be found in the following request attributes:

     javax.servlet.include.request_uri
     javax.servlet.include.context_path
     javax.servlet.include.servlet_path
     javax.servlet.include.path_info
     javax.servlet.include.query_string

For <jsp:forward>, the new URL will be returned by request.getRequestURL(), and the original request's information will be found in the following request attributes:

     javax.servlet.forward.request_uri
     javax.servlet.forward.context_path
     javax.servlet.forward.servlet_path
     javax.servlet.forward.path_info
     javax.servlet.forward.query_string

These are set out in section 8.3 and 8.4 of the Servlet 2.4 specification.

However, be aware that this information is only preserved for internally-dispatched requests. If you have a front-end web-server, or dispatch outside of the current container, these values will be null. In other words, you may have no way to find the original request URL.


Just did a slight tidy of the solution by Ballsacian1

String currentURL = null;
if( request.getAttribute("javax.servlet.forward.request_uri") != null ){
    currentURL = (String)request.getAttribute("javax.servlet.forward.request_uri");
}
if( currentURL != null && request.getAttribute("javax.servlet.include.query_string") != null ){
    currentURL += "?" + request.getQueryString();
}

The null checks are going to run a lot more efficiently than String comparisons.


String activePage = "";
    // using getAttribute allows us to get the orginal url out of the page when a forward has taken place.
    String queryString = "?"+request.getAttribute("javax.servlet.forward.query_string");
    String requestURI = ""+request.getAttribute("javax.servlet.forward.request_uri");
    if(requestURI == "null") {
        // using getAttribute allows us to get the orginal url out of the page when a include has taken place.
        queryString = "?"+request.getAttribute("javax.servlet.include.query_string");
        requestURI = ""+request.getAttribute("javax.servlet.include.request_uri");
    }
    if(requestURI == "null") {
        queryString = "?"+request.getQueryString();
        requestURI = request.getRequestURI();
    }
    if(queryString.equals("?null")) queryString = "";
    activePage = requestURI+queryString;

${requestScope['javax.servlet.forward.query_string']} -- if you access it form jsp, using Expression Language