0

I am trying to get the complete URL from HttpServletRequest object. I got various ways of doing it. One of the way is to combine the requestURL with queryString. My situation is that there is a ? at the end with no query params. How do I identify that my URL has a ? at the end.

The URL is something like : http://www.xyz.com/path/id?

I need to consider ? as part of the id. (Client requirement :))

The code I am trying is:

public static 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();
}
}
Rahul Bansal
  • 152
  • 10

2 Answers2

0

In this case it will not add extra ? at end if return queryString is null or empty.

if (queryString != null && !queryString.trim().equals("")) {
  return requestURL.append('?').append(queryString).toString();    
} else {
  return requestURL.toString();    
}

How do I identify that my URL has a ? at the end. For this you can check

 if (queryString == null || queryString.trim().equals("")) {
   In this case just check requestUrl last char. //String data = requestUrl.substring(0, requestUrl.length-1);
   check data has "?"
 }
Jayesh
  • 6,047
  • 13
  • 49
  • 81
0

I believe the difference you are looking for is this:

When a url does not have a question mark, the request.getQueryString() result will be null.

When a url ends with a question mark but has no query string, the request.getQueryString() result will be an empty string or "".

So, you should be able to check like this:

String queryString = request.getQueryString();
if (queryString == null) {
    // There was no question mark. React accordingly.
} else if ("".equals(queryString)) {
    // The URL ended with a question mark and had no query parameters. React accordingly.
} else {
    // The URL ended with a question mark AND parameters. React accordingly.
}
MattSenter
  • 3,060
  • 18
  • 18