如何在 Tomcat 上的 Web 应用程序中提供静态文件 [英] How to serve static files in my web application on Tomcat

查看:31
本文介绍了如何在 Tomcat 上的 Web 应用程序中提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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 get a 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.

推荐答案

我有一些路径问题,我无法解决它们,我搜索了一遍又一遍,但仍然无法正常工作,我收到了 404(未找到).../CpdApplication/Chart.js

I have some path problems, and I can't resolve them, I searched over and over again and still not working, I get a 404 (Not Found) for .../CpdApplication/Chart.js

确实,在编写 <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 中的

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