My JSP and Servlets professor handed me down this code as a nice way to reconstruct an original request URL and avoid the temptation to ever hard-code a URL, which is also really bad practice. It’s really useful for getting out of tricky situations. In my case, I needed a way to go back to the http:// protocol after having accessed resources using SSL. I found that if I simply used RequestDispatcher, even when the resource I was requesting wasn’t included among those restricted ones, the protocol continued to be https:// . I had searched everywhere for a way to fix this and this is what he suggested.
Example: // 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; }