Getting the Requesting URL in a Servlet
A servlet container breaks up the requesting URL into convenientcomponents for the servlet. The standard API does not require theoriginal requesting URL to be saved and therefore it is not possibleto get the requesting URL exactly as the client sent it. However, afunctional equivalent of the original URL can be constructed. Thefollowing example assumes the original requesting URL is:
The most convenient method for reconstructing the original URL is touse
ServletRequest.getRequestURL(), which returns all but thequery string. Adding the query string reconstructs an equivalent ofthe original requesting URL:
If the hostname is not needed,
ServletRequest.getRequestURI()should be used:
The original URL can also be reconstructed from more basic componentsavailable to the servlet:
http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
// 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; }
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789 public static String getUrl2(HttpServletRequest req) { String reqUri = req.getRequestURI().toString(); String queryString = req.getQueryString(); // d=789 if (queryString != null) { reqUri += "?"+queryString; } return reqUri; }
// http://hostname.com:80/mywebapp/servlet/MyServlet/a/b;c=123?d=789 public static String getUrl3(HttpServletRequest req) { String scheme = req.getScheme(); // http String serverName = req.getServerName(); // hostname.com int serverPort = req.getServerPort(); // 80 String contextPath = req.getContextPath(); // /mywebapp String servletPath = req.getServletPath(); // /servlet/MyServlet String pathInfo = req.getPathInfo(); // /a/b;c=123 String queryString = req.getQueryString(); // d=789 // Reconstruct original requesting URL String url = scheme+"://"+serverName+":"+serverPort+contextPath+servletPath; if (pathInfo != null) { url += pathInfo; } if (queryString != null) { url += "?"+queryString; } return url; }