views:

557

answers:

4

I have an HttpServletRequest object.

How do I get the complete and exact URL that cause this call to arrive at my servlet?

Or at least as accurately as possible, as there are perhaps things that can be regenerated (the order of the parameters, perhaps).

+4  A: 

HttpServletRequest

getRequestURL() - Reconstructs the URL the client used to make the request.

getQueryString() - Returns the query string that is contained in the request URL after the path.

E.g.

String fullURL = request.getRequestURL().append("?" + 
     request.getQueryString()).toString();
Bozho
You copied the description from getRequestURI (wrong) but use getRequestURL in the code (right).
Vinko Vrsalovic
thanks, miscopy-pasting :)
Bozho
You need to conditionally check if the query string is empty.
Adam Gent
A: 

Combining the results of getRequestURL() and getQueryString() should get you the desired result.

Michael Borgwardt
A: 

HttpUtil being deprecated, this is the correct method

StringBuffer url = req.getRequestURL();
String queryString = req.getQueryString();
if (queryString != null) {
    url.append('?');
    url.append(queryString);
}
String requestURL = url.toString();
Vinko Vrsalovic
this class is deprecated.
Bozho
+2  A: 
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789

public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}
Teja Kantamneni
You're ignoring the advantage of `StringBuffer`.
BalusC
Yes. I accept it, but its only two additional objects I guess.
Teja Kantamneni