如何为request.getRequestDispatcher()指定.JSP文件的路径? [英] How specify path to .JSP file for request.getRequestDispatcher()?

查看:2709
本文介绍了如何为request.getRequestDispatcher()指定.JSP文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对request.getContextPath()的含义感到困惑。我的文件布局如下:

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

MyPage.jsp 中,我能够通过

<script src="${pageContext.request.contextPath}/Resources/Scripts/MyScript.js">

<img src="${pageContext.request.contextPath}/Resources/MyImage.img">

从此我得出结论 $ {pageContext.request.contextPath} 动态解析为WebContent文件夹,我理解这将解析为此文件夹,无论它的名称是什么。这是有效的。

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.

然而,从所有这一点我得出结论,回到我的.java代码 request.getContextPath()也会动态解析为WebContent。但是当我尝试使用从 request.getContextPath()+/ WEB-INF形成的字符串从.java代码转发到 MyPage.jsp 时/JSP/MyPage.jsp,无法找到JSP;这导致404错误 - 请求的资源(/MyServer/WEB-INF/JSP/MyPage.jsp)不可用。如果我调用/ WEB-INF / JSP / MyPage.jsp,我们将启动JSP页面。有人可以解释为什么预先挂起的 request.getContextPath()导致它失败,还有什么我应该用来确保始终解决.JSP的路径?

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?

推荐答案

RequestDispatcher 已经相对于当前的Web应用程序上下文运行。您不需要预先添加上下文路径。

The RequestDispatcher operates already relative to the current web application context. You don't need to prepend the context path.

为什么在HTML中链接的JS / CSS / image / etc资源需要它只是因为它是webbrowser谁必须通过适当的URL路径下载它们。常见的启动者错误是他们认为是网络服务器必须以某种方式通过本地磁盘文件系统路径自动包含它们。因此不是这样。它实际上是一个URL,就像你在浏览器的地址栏中输入的那样。

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.

  • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

这篇关于如何为request.getRequestDispatcher()指定.JSP文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆