且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Tomcat 上的 Web 应用程序中提供静态文件

更新时间:2022-12-05 10:08:27

我有一些路径问题,我无法解决它们,我搜索了一遍又一遍,但仍然无法正常工作,我收到了 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 中的 标记.此外,请确保您重新部署您的网络应用程序以更新您的 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).