问题
I am confused about the meaning of request.getContextPath(). My file layout is as follows:
MyServer/WebContent:
/Resources/MyImage.jpg
/Resources/Scripts/MyScript.js
/WEB-INF/JSP/MyPage.jsp
In the MyPage.jsp
I am able to locate the JavaScript and image by
<script src="${pageContext.request.contextPath}/Resources/Scripts/MyScript.js">
and
<img src="${pageContext.request.contextPath}/Resources/MyImage.img">
From this I concluded that ${pageContext.request.contextPath}
dynamically resolved to the "WebContent" folder and it is my understanding that this will resolve to this folder no matter what it is named. That is working.
However, from all of this I concluded that back in my .java code request.getContextPath()
would also dynamically resolve to "WebContent". But when I try to forward from the .java code to MyPage.jsp
using the string formed from request.getContextPath()+"/WEB-INF/JSP/MyPage.jsp"
, the JSP cannot be found; this results in a 404 Error - "The Requested Resource (/MyServer/WEB-INF/JSP/MyPage.jsp) is not available". If I call "/WEB-INF/JSP/MyPage.jsp"
we launch the JSP page. Can someone explain why pre-pending request.getContextPath()
causes this to fail and is there something else I should use to ensure that the path to the .JSP is always resolved?
回答1:
The RequestDispatcher
operates already relative to the current web application context. You don't need to prepend the context path.
Why it is required for JS/CSS/image/etc resources which are linked in HTML is simply because it's the webbrowser who has got to download them by a proper URL path. A common starters mistake is that they think that it's the webserver who has got to auto-include them by a local disk file system path somehow. This is thus not true. It has really to be an URL, like the one as you enter in browser's address bar.
See also:
- Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
来源:https://stackoverflow.com/questions/9980283/how-specify-path-to-jsp-file-for-request-getrequestdispatcher