Q: HttpServletRequest to complete URL

D: 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).

Test Case #2


File ID: #2222268-5-cc


private String getFullURL(HttpServletRequest request) {
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();
    if (queryString = = null) {
        return requestURL.toString();
    } else {
        return requestURL.append('?').append(queryString).toString();
    }
}

  1. You need to conditionally check if the query string is empty.
  2. A StringBuffer is returned on purpose, so that you easily can add on more stash. Since this is specified on the javadoc, it would be extremely absurd of the implementation to expect that the returned StringBuffer would not be modified by the caller - hence, this is cool.
  3. You are also mutating the StringBuffer backing the request URL. If the request implementation is not making a defensive copy that's a very good way to introduce strange behavior and bugs in other parts of code that expect it in it's original form.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: