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).
The ServletRequest and HttpServletRequest classes hold all of the accessible information about the client and the server. HttpServletRequest is a subclass of ServletRequest, and is passed to each servlet handler method (such as doGet(..), doPut(..), etc.)
In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.
The function getRequestURI() returns the complete requested URI. This includes the deployment folder and servlet-mapping string. It will also return all extra path information.
A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest .
The HttpServletRequest
has the following methods:
getRequestURL()
- returns the part of the full URL before query string separator character ?
getQueryString()
- returns the part of the full URL after query string separator character ?
So, to get the full URL, just do:
public static String getFullURL(HttpServletRequest request) { StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString()); String queryString = request.getQueryString(); if (queryString == null) { return requestURL.toString(); } else { return requestURL.append('?').append(queryString).toString(); } }
I use this method:
public static String getURL(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 StringBuilder url = new StringBuilder(); url.append(scheme).append("://").append(serverName); if (serverPort != 80 && serverPort != 443) { url.append(":").append(serverPort); } url.append(contextPath).append(servletPath); if (pathInfo != null) { url.append(pathInfo); } if (queryString != null) { url.append("?").append(queryString); } return url.toString(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With