javahttpservlets

HttpServletRequest to complete URL


I have an HttpServletRequest object.

How do I get the complete and exact URL that caused 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).


Solution

  • The HttpServletRequest has the following methods:

    So, to get the full URL, just do:

    public static String getFullURL(HttpServletRequest request) {
        StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
        String queryString = request.getQueryString();
    
        if (queryString == null) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }