Search code examples
javajspservletsforwardrequestdispatcher

Forwarding a request from servlet to JSP using RequestDispatcher doesn't hide the target URL


In a nutshell, I have a servlet that forwards a GET request to a JSP, and I would like to "hide" the target URL from the user.

My setup is as follows:

  1. A servlet, mapped to URL "www.mydomain.com/pages/page1"
  2. A JSP, at address "/WEB-INF/pages/page1.jsp", relative to the application root. The JSP resides in the WEB-INF directory, in order to not be accessible directly from the browser.

Upon access from the browser, the servlet pre-processes the incoming GET request, and forwards it to the JSP using the following code-snippet:

request.getRequestDispatcher("/WEB-INF/pages/page1.jsp").forward(request, response);

The desired behaviour is for the browser to maintain the URL "www.mydomain.com/pages/page1", while the user sees the contents of the JSP.

Unfortunately, the browser consistently switches to display the JSP's URL: "www.mydomain.com/WEB-INF/pages/page1.jsp" (Tested in Chrome and Firefox)

Can anyone tell me, what could be causing this behaviour?

Source: This solution is described in this CodeRanch answer, in which they are successful at "hiding" the address to the JSP: http://www.coderanch.com/t/618800/JSP/java/Url-hiding


Solution

  • Having done some extensive poking around my implementation, I was able to isolate the cause of this issue. The exact source code is too complex to post here, and is in fact irrelevant.

    The problem was caused by this obscure line of Javascript, pulled into the JSP from a separate utility class, via a scriptlet (obsolete practice).

    <script type='text/javascript'>
      window.history.replaceState(null, document.title, sanitizedURL);
    </script>
    

    For legacy reasons, the page URL was being "sanitized" by removing a part of its query string, and then "replacing the state of the window history" took place. I'm not sure whether that qualifies as a page re-load, but the unwanted side effect is surfacing of the actual resource URL, "www.mydomain.com/WEB-INF/pages/page1.jsp"

    Bottom line: if you're experiencing a similar issue, try looking for Javascript that's messing with the window/document state