By design, getRequestURL() you get the full URL, not just the query string.
In the HttpServletRequest you can get the individual parts of the URI using the following methods:
// Example: http://myhost:8080/people?lastname=Fox&age=30 String uri = request.getScheme() + "://" + // "http" + ":// request.getServerName() + // "myhost" ":" + // ":" request.getServerPort() + // "8080" request.getRequestURI() + // "/people" "?" + // "?" request.getQueryString(); // "lastname=Fox&age=30"
.getScheme() will give you "https" if it was a https://domain request..getServerName() gives domain to http(s)://domain ..getServerPort() will provide you with a port.
Use the snippet below:
String uri = request.getScheme() + "://" + request.getServerName() + ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) + request.getRequestURI() + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
This snippet above will get the full URI, hiding the port, if used by default, and not add "?" and a query string if the latter was not provided.
Proxied Requests
Please note that if your request passes through a proxy server, you need to look at the X-Forwarded-Proto header, as the scheme can be changed:
request.getHeader("X-Forwarded-Proto")
Also, a generic X-Forwarded-For header that shows the source IP address of the request instead of proxys-IP.
request.getHeader("X-Forwarded-For")
If you yourself are responsible for the proxy configuration / load balancing, you need to make sure that these headers are configured during forwarding.
acdcjunior May 21 '13 at 16:52 2013-05-21 16:52
source share