Last active
August 7, 2017 02:39
-
-
Save ziesemer/700376d8da8c60585438 to your computer and use it in GitHub Desktop.
A faster, "complete" Java HttpServletRequest.getRequestUrl() replacement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.servlet.http.HttpServletRequest; | |
public class GetRequestUrl{ | |
/** | |
* <p>A faster replacement for {@link HttpServletRequest#getRequestURL()} | |
* (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder}) | |
* that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p> | |
* <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438" | |
* >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p> | |
* @author Mark A. Ziesemer | |
* <a href="http://www.ziesemer.com."><www.ziesemer.com></a> | |
*/ | |
public String getRequestUrl(final HttpServletRequest req){ | |
final String scheme = req.getScheme(); | |
final int port = req.getServerPort(); | |
final StringBuilder url = new StringBuilder(256); | |
url.append(scheme); | |
url.append("://"); | |
url.append(req.getServerName()); | |
if(!(("http".equals(scheme) && (port == 0 || port == 80)) | |
|| ("https".equals(scheme) && port == 443))){ | |
url.append(':'); | |
url.append(port); | |
} | |
url.append(req.getRequestURI()); | |
final String qs = req.getQueryString(); | |
if(qs != null){ | |
url.append('?'); | |
url.append(qs); | |
} | |
final String result = url.toString(); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also: