Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - How to serve static files in my web application on Tomcat

I have this servlet based web application project in eclipse and want to append some html tags like <script src="Chart.js">.

The folder structure is:

  • 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

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.

The problem is when I want to append <script src='Chart.js'></script>, Tomcat cannot resolve the Chart.js static file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...