问题描述
我在 Eclipse 中有这个基于 servlet 的 Web 应用程序项目,并且想要附加一些 html 标签,例如 <script src="Chart.js">
.
I have this servlet based web application project in eclipse and want to append some html tags like <script src="Chart.js">
.
文件夹结构为:
- C:/apache-tomcat-7.0.53/
- 我的工作区在 D:/../../workplace/CpdApplication/src/cpd/MyServlet.java
- cpd 包含:MyServlet.java、Chart.js 等文件.
- CpdApplication/WebContent/META-INF/web.xml
我有一些路径问题,我无法解决它们,我一遍又一遍地搜索,但仍然无法正常工作,我明白了http://localhost:8080/CpdApplication/Chart.js
的 404(未找到).
I have some path problems, and I can't resolve them, I searched over and over again and still not working, I geta 404 (Not Found) for http://localhost:8080/CpdApplication/Chart.js
.
问题是当我想追加<script src='Chart.js'></script>
时,Tomcat无法解析Chart.js
静态文件.
The problem is when I want to append <script src='Chart.js'></script>
, Tomcat cannot resolve the Chart.js
static file.
推荐答案
确实,在编写 <script src="/Chart.js"/>
时,您是在告诉浏览器发出自己的、单独的 HTTP 请求以获取 JavaScript 文件.为此:
Indeed, when writing <script src="/Chart.js"/>
you are telling the browser to make its own, separate HTTP request to get the JavaScript file. For this to work:
- servlet 容器需要能够提供静态文件
- 为此,您需要在 web.xml 中有一个 servlet-mapping 来提供静态文件(即默认servlet).
- The servlet container needs to be able to serve static files
- To this end, you need to have a servlet-mapping inside your web.xml to serve static files (ie. the default servlet).
应该这样做:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/js/*</url-pattern>
</servlet-mapping>
然后将您的 Chart.js
放在以下文件夹中:WebContent/js/
并且它应该可以工作.
Then place your Chart.js
in the following folder: WebContent/js/
and it should work.
EDIT:当然,您需要更新 HTML 中的 标记.此外,请确保您重新部署您的网络应用程序以更新您的 servlet 容器(我认为是 Tomcat)上的 web.xml.
EDIT: Of course, you'll need to update the <script>
tag in your HTML. Also, make sure that you redeploy your web app to update web.xml on your servlet container (Tomcat I presume).
这篇关于如何在 Tomcat 上的 Web 应用程序中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!