Java 怎么在servlet中获取请求的URL

2019年8月17日22:07:23 评论 45

1.简介

Java 怎么在servlet中获取请求的URL?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}

public static String getUrl2(HttpServletRequest req) {
    String reqUri = req.getRequestURI().toString();
    String queryString = req.getQueryString();   
    if (queryString != null) {
        reqUri += "?"+queryString;
    }
    return reqUri;
}

public static String getUrl3(HttpServletRequest req) {
    String scheme = req.getScheme();             
    String serverName = req.getServerName();     
    int serverPort = req.getServerPort();        
    String contextPath = req.getContextPath();   
    String servletPath = req.getServletPath();   
    String pathInfo = req.getPathInfo();         
    String queryString = req.getQueryString();          

    
    String url = scheme+":
    if (pathInfo != null) {
        url += pathInfo;
    }
    if (queryString != null) {
        url += "?"+queryString;
    }
    return url;
}

 

3.总结

示例代码演示了 Java 怎么在servlet中获取请求的URL,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: