How to serve static files in my web application on Tomcat

It seems to me like Chart.js is stored in the same folder with your servlet source.

Usually you should have a structure like this one (I have simplified it):

/css/your-css.css
/js/your-script.js
/src/your-package/YourServlet.java

Whenever you run your application, your compiler creates a set of files that will be copied to your web container. The copied files do not include your src folder, but instead a copy of your built (compiled) classes. All other files (with some exceptions that we should not care about right now) must be outside your src folder in order to get copied.

Try moving your JS inside a js directory outside your src directory. Then, link it like this:

<script src='/Your-Context-Path/js/Chart.js'>

There must be a function to get your context path automatically, I think it is

ServletContext.getContextPath()

You can read about it here.

That should make the trick.


This is works for me. Thanks 沖原ハーベスト

welcome.jsp

  <head>
    <script src="resources/js/jsx/browser.min.js"></script>
    <script src="resources/js/react/react.min.js"></script>
    <script src="resources/js/react/react-dom.min.js"></script>
    <script src="resources/js/main.js"></script>
    <link rel="stylesheet" type="text/css" href="resources/css/style.css">
  </head>

File hierarchy tree

enter image description here

Web.xml

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

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

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:

  • 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).

This should do:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/js/*</url-pattern>
</servlet-mapping>

Then place your Chart.js in the following folder: WebContent/js/ and it should work.

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).