有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jsp Java HttpServletRequest在浏览器URL栏中获取URL

因此,我尝试使用Java的请求对象获取页面的当前URL。我一直在使用请求。getRequestURI()来执行此操作,但我注意到,当java类将我从servlet请求重新路由到另一个页面时,getRequestURI会给出该地址,而不是在浏览器中键入并仍在浏览器中显示的原始URL

例如:\AdvancedSearch:
getRequestURI()返回“\subdir\search\search.jsp”

我正在寻找一种方法来获取浏览器所看到的URL,而不是页面所知道的仅仅是servlet包装器


共 (6) 个答案

  1. # 1 楼答案

    只是稍微整理了一下Ballsacian1的解决方案

    String currentURL = null;
    if( request.getAttribute("javax.servlet.forward.request_uri") != null ){
        currentURL = (String)request.getAttribute("javax.servlet.forward.request_uri");
    }
    if( currentURL != null && request.getAttribute("javax.servlet.include.query_string") != null ){
        currentURL += "?" + request.getQueryString();
    }
    

    空检查将比字符串比较更有效地运行

  2. # 2 楼答案

    你能试试这个吗

    <%=request.getRequestURL().toString()%>
    
  3. # 3 楼答案

    如果当前请求来自“应用服务器内部”转发或包含,则应用服务器应将请求信息保留为请求属性。具体属性及其包含的内容取决于您是在进行转发还是包含

    对于<jsp:include>,原始父URL将由request.getRequestURL()返回,有关包含页面的信息将在以下请求属性中找到:

         javax.servlet.include.request_uri
         javax.servlet.include.context_path
         javax.servlet.include.servlet_path
         javax.servlet.include.path_info
         javax.servlet.include.query_string
    

    对于<jsp:forward>,新URL将由request.getRequestURL()返回,原始请求的信息将在以下请求属性中找到:

         javax.servlet.forward.request_uri
         javax.servlet.forward.context_path
         javax.servlet.forward.servlet_path
         javax.servlet.forward.path_info
         javax.servlet.forward.query_string
    

    Servlet 2.4规范的第8.3节和第8.4节对此进行了阐述

    但是,请注意,此信息仅为内部发送的请求保留。如果您有一个前端web服务器,或在当前容器之外调度,这些值将为空。换句话说,您可能无法找到原始请求URL

  4. # 4 楼答案

    String activePage = "";
        // using getAttribute allows us to get the orginal url out of the page when a forward has taken place.
        String queryString = "?"+request.getAttribute("javax.servlet.forward.query_string");
        String requestURI = ""+request.getAttribute("javax.servlet.forward.request_uri");
        if(requestURI == "null") {
            // using getAttribute allows us to get the orginal url out of the page when a include has taken place.
            queryString = "?"+request.getAttribute("javax.servlet.include.query_string");
            requestURI = ""+request.getAttribute("javax.servlet.include.request_uri");
        }
        if(requestURI == "null") {
            queryString = "?"+request.getQueryString();
            requestURI = request.getRequestURI();
        }
        if(queryString.equals("?null")) queryString = "";
        activePage = requestURI+queryString;
    
  5. # 5 楼答案

    要在不知道请求内部流状态的情况下获取HTTP请求路径,请使用以下方法:

    public String getUri(HttpServletRequest request) {
        String r = (String) request.getAttribute("javax.servlet.forward.request_uri");
        return r == null ? request.getRequestURI() : r;
    }
    
  6. # 6 楼答案

    ${requestScope['javax.servlet.forward.query_string']} --如果您使用表达式语言从jsp访问它