http://www.exampledepot.com/egs/javax.servlet/GetReqUrl.html
A servlet container breaks up the requesting URL into convenient components for the servlet. The standard API does not require the original requesting URL to be saved and therefore it is not possible to get the requesting URL exactly as the client sent it. However, a functional equivalent of the original URL can be constructed. The following example assumes the original requesting URL is:
A servlet container breaks up the requesting URL into convenient components for the servlet. The standard API does not require the original requesting URL to be saved and therefore it is not possible to get the requesting URL exactly as the client sent it. However, a functional equivalent of the original URL can be constructed. The following example assumes the original requesting URL is:
http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789The most convenient method for reconstructing the original URL is to use
ServletRequest.getRequestURL()
, which returns all but the
query string. Adding the query string reconstructs an equivalent of
the original requesting URL:
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789If the hostname is not needed,
public static String getUrl(HttpServletRequest req) {
String reqUrl = req.getRequestURL().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUrl += "?"+queryString;
}
return reqUrl;
}
ServletRequest.getRequestURI()
should be used:
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789The original URL can also be reconstructed from more basic components available to the servlet:
public static String getUrl2(HttpServletRequest req) {
String reqUri = req.getRequestURI().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUri += "?"+queryString;
}
return reqUri;
}
// 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;
}
'프로그래밍 > Web' 카테고리의 다른 글
[HTTP] HTTP BASIC-AUTH (0) | 2009.02.27 |
---|---|
[Servlet] Servlet에서 request의 input stream을 이용해서 읽어들일 때 (0) | 2009.02.19 |
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |