Tag: servlet

[問題] servlet 如何獲得 request URL

假設 Request Servlet URL 如下:

http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=456

獲得 RequestURL 完整路徑:

/**
*
* @param req
* @return http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=456
*/
public static String getRequestURL(HttpServletRequest req) {
   String reqUrl = req.getRequestURL().toString();
   String queryString = req.getQueryString(); // d=456
   if (queryString != null) {
      reqUrl += "?"+queryString;
   }
   return reqUrl;
}

獲得 Request URI:

/**
*
* @param req
* @return /mywebapp/servlet/MyServlet/a/b;c=123?d=456
*/
public static String getRequestURI(HttpServletRequest req) {
   String reqUri = req.getRequestURI().toString();
   String queryString = req.getQueryString(); // d=456
   if (queryString != null) {
      reqUri += "?"+queryString;
   }
   return reqUri;
}

獲得 Request Root URL:

/**
*
* @param req
* @return http://hostname.com/mywebapp
*/
public static String getRootURL(HttpServletRequest req) {
   String scheme = req.getScheme(); // http
   String serverName = req.getServerName(); // hostname.com
   int serverPort = req.getServerPort(); // 80
   String contextPath = req.getContextPath(); // /mywebapp
// String pathInfo = req.getPathInfo(); // /a/b;c=123
// String queryString = req.getQueryString(); // d=456
   String url = scheme+"://"+serverName+":"+serverPort+contextPath;
   return url;
}
Tags : ,