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

查看:461
本文介绍了如何在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

  • C:/apache-tomcat-7.0.53/
  • my workspace is in D:/../../workplace/CpdApplication/src/cpd/MyServlet.java
  • cpd contains: MyServlet.java, Chart.js and other files.
  • CpdApplication/WebContent/META-INF/web.xml

我有一些路径问题,我无法解决它们,我一遍又一遍地搜索但仍然无法工作,我得到
a 404(未找到) http:// localhost:8080 / 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 http://localhost:8080/CpdApplication/Chart.js.

问题是当我想追加< script src ='Chart.js'>< / script> ,Tomcat无法解析 Chart.js 静态文件。 / p>

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.

编辑:当然,您需要更新< script> HTML中的标记。此外,请确保重新部署Web应用程序以更新servlet容器上的web.xml(我假设为Tomcat)。

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应用程序中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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