Getting the Requesting URL in a Servlet

Getting the Requesting URL in a Servlet

A servlet container breaks up the requesting URL into convenientcomponents for the servlet. The standard API does not require theoriginal requesting URL to be saved and therefore it is not possibleto get the requesting URL exactly as the client sent it. However, afunctional equivalent of the original URL can be constructed. Thefollowing example assumes the original requesting URL is:
http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
The most convenient method for reconstructing the original URL is touse ServletRequest.getRequestURL(), which returns all but thequery string. Adding the query string reconstructs an equivalent ofthe original requesting URL:
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}
If the hostname is not needed, ServletRequest.getRequestURI()should be used:
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl2(HttpServletRequest req) {
    String reqUri = req.getRequestURI().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUri += "?"+queryString;
    }
    return reqUri;
}
The original URL can also be reconstructed from more basic componentsavailable to the servlet:
// 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值