When in a JSP or Servlet it is often useful to retrieve the URL of the current JSP, to offer as a link or possibly bookmarking. This can be achieved in two steps.
You must first get the hostname and directory structure. Using a google URL as an example this is all the text up to but not including the ? character: http://www.google.ie/search?q=www.tomred.net. This can be achieved using a method available in the JSP request Java JSP Implicit Objects request.getRequestURL().
Secondly you retrieve the query elements of the URL these elements are all the parts after the ? but not including it: http://www.google.ie/search?q=www.tomred.net.
Finally you put these together to get the full string reconstructed remembering to place the ? character back in.
String url = request.getRequestURL();
if (request.getQueryString() != null)
url += "?" + request.getQueryString();
Important: It is not necessary (and bad programming practice) to use request.getQueryString() if you are looking for the parameters names or values sent to the page these can be easily found using the request.getParameterNames() and request.getParameter() respectively. This is explained in JSP accessing the parameter value sent in URL or HTTP POST.


