As another performance-focused method for reuse: It should be easier to obtain the "complete" URL from a HttpServletRequest in Java.
This is even a popular question on Stack Overflow: HttpServletRequest to complete URL - though I have various issues with each of the current answers.
Following is a self-written version that I've been using for a number of years now.
I previously had posted it as a Gist , and since incorporated it into my MarkUtils-Web library in WebUtils
- Checkstyle-approved and JUnit-tested:
import javax.servlet.http.HttpServletRequest;
public class GetRequestUrl{
/**
* 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}.
* https://gist.github.com/ziesemer/700376d8da8c60585438
* @author Mark A. Ziesemer
* <www.ziesemer.com>
*/
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;
}
}
No comments:
Post a Comment