19

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.

VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
que1326
  • 2,227
  • 4
  • 41
  • 58
  • Java **is not** JavaScript. Please use the right tags for your questions. – Luiggi Mendoza Apr 09 '14 at 14:41
  • @ Luiggi Mendoza I added JavaScript tag to my post, but I don t know why it s not posted ... – que1326 Apr 09 '14 at 14:42
  • Your problem is about Java, not, JavaScript. In fact, your problem is about where you have placed your resources files (JS, CSS, images, etc). Please remove the unrelevant code (Servlet doesn't play any role here, neither web.xml) and post the relevant HTML code that is generated and how your files are distributed in your application. – Luiggi Mendoza Apr 09 '14 at 14:45
  • Edited: the only problem is the path...404 file not found, or I can t load it because of the tomcat server – que1326 Apr 09 '14 at 14:49
  • Ok, where do you have this Chart.js file stored, what's the name of the folder? – Luiggi Mendoza Apr 09 '14 at 14:52
  • I have it in my D: workspace , my_project_name in every folder/subfolder/ etc, just to be safe it will be loaded from somewhere... but it doesen t. – que1326 Apr 09 '14 at 14:57
  • 1
    @LuiggiMendoza: Actually the deployment descriptor web.xml is relevant since the OP is trying to load a static resource. – VH-NZZ Apr 10 '14 at 08:57
  • @okiharaherbst it is not. The main problem is a path problem. The web.xml doesn't solve these kind of problems. – Luiggi Mendoza Apr 10 '14 at 13:53
  • @LuiggiMendoza Why do you think that it's a path problem? It's a static resource and you need a default mapping in Tomcat to serve such resources. web.xml is where you declare such mappings, isn't it? – VH-NZZ Apr 10 '14 at 13:56
  • @okiharaherbst AFAIK if you have your resources in a folder in root, let's call it *res*, then put all the resources inside it, for example *res/Chart.js*, then you can always access to it using `${request.contextPath}/res/Chart.js` despite the location of your page in the folders of your application. – Luiggi Mendoza Apr 10 '14 at 13:59
  • @LuiggiMendoza err no. What do you mean by 'page' in this 'context' (no pun intended). It's URL–servlet mapping. For static resources, read up here: http://tomcat.apache.org/tomcat-7.0-doc/default-servlet.html – VH-NZZ Apr 10 '14 at 14:05
  • @okiharaherbst that looks like tomcat specific. Would that work on GlassFish or WebSpehere? If not, then it would be better using the usual approach. Note that it works for me and for lot of people. – Luiggi Mendoza Apr 10 '14 at 14:08
  • @LuiggiMendoza: That almost certainly would, anything else would be a special case. For instance, there is a similar `DefaultServlet` in Glassfish and I don't know about WebSphere. FYI, the OP tagged the question with _Tomcat_. – VH-NZZ Apr 10 '14 at 14:16

5 Answers5

19

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

VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
  • I replaced with MyServlet in my web.xml and still not working – que1326 Apr 10 '14 at 12:37
  • 1
    @VladRadulescu No, The whole crux is the `default` servlet! If you write `MyServlet` Tomcat will map requests to `/js/*` to MyServlet which is _not_ what you want. Also, once you have `/js/*` in your web.xml, create a `WebContent/js/` folder and place `Chart.js` there. Then your request should be localhost:8080/js/Chart.js (don't forget /js first). If you deploy it within a non-root context, the context name should prefix /js of course. On a side note, MyServlet is mapped nowhere in your web.xml. – VH-NZZ Apr 10 '14 at 13:01
  • .. but that's all good if you have the `@WebServlet` annotation. – VH-NZZ Apr 10 '14 at 13:19
  • THANK YOU VERY MUCH SIR !!! my resource has been loaded., I will send u the link download application for free when I finish it :d – que1326 Apr 10 '14 at 14:13
  • 2
    @VladRadulescu No magic involved (http://tomcat.apache.org/tomcat-7.0-doc/default-servlet.html). Just mark the answer as accepted if you're happy with it. Looking forward to seeing your app in motion! – VH-NZZ Apr 10 '14 at 14:18
  • It would be worth adding that the default servlet also has a default mapping, with url-pattern '/', main reason to add to your own web.xml is to restrict static resources to certain mappings. See e.g. https://tomcat.apache.org/tomcat-5.5-doc/default-servlet.html – drrob Sep 07 '15 at 13:48
  • 1
    @VladRadulescu Still waiting for the download link... :) – VH-NZZ Jun 22 '16 at 11:51
  • @ okiharaherbst what download link ? – que1326 Jun 22 '16 at 11:52
  • @VladRadulescu See your comment from Apr 10 '14 above. – VH-NZZ Jun 22 '16 at 15:32
  • @ okiharaherbst, well, it was 2 years ago, can't remember well, what I did with it :p – que1326 Jun 23 '16 at 11:20
8

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>
Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47
2

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.

Andres
  • 1,090
  • 14
  • 30
  • this is my workplace path: D:\trash\mem stick8 GB\Vladtisu\workspace\CpdApplication\js and in my servlet > script tag > Still not working ! – que1326 Apr 09 '14 at 15:12
  • what files do you have inside that folder? – Andres Apr 09 '14 at 15:14
  • Inside it I have Chart.js – que1326 Apr 09 '14 at 15:16
  • ok, so I understand that you have also something like this: D:\trash\mem stick8 GB\Vladtisu\workspace\CpdApplication\src\package\servlet-source-code? – Andres Apr 09 '14 at 15:17
  • yes, I replaced my path with and I get this Not allowed to load local resource: file:///D:/trash/mem%20stick8%20GB/Vladtisu/workspace/CpdApplication/js/Chart.js – que1326 Apr 09 '14 at 15:20
  • 1
    I reread your previous comment. file://D:/trash/mem stick8 GB/Vladtisu/workspace/CpdApplication **is not your context path**. It is usually the name of your project. In your case I think it is **CpdApplication** so, move your JS outside your src folder and then make your link point to it like this: ** – Andres Apr 09 '14 at 15:41
  • Failed to load resource: the server responded with a status of 404 (Not Found) (This is very frustrating :)) ) – que1326 Apr 10 '14 at 08:15
  • 2
    The context path should not appear in the src attribute of the script tag. Moreover, Tomcat will map requests to servlets. If you want to serve static resources, you should either use the default servlet or create your own. In both cases, you should create a mapping in web.xml – VH-NZZ Apr 10 '14 at 11:20
2

As @Andy replied, you need to set all your resource (JS, CSS, images, etc.) in a folder in your application, then access to them using <context_path>/folder/to/your/resource/<resource_name>.<ext>. Here's a sample of how to do it:

  • Create a folder inside the root folder (usually named web or WebContent) of your web application with name res.
  • Inside res, create a folder called js to put all the JavaScript files there. You may create a css folder to handle all your CSS stylesheets, img for images, and on.
  • In your view, this mean, your JSP, you should access to your resources via context path.

This is how your application folders should look:

- WebContent
  - res
    - js
      Chart.js

In your JSP:

<script src="${request.contextPath}/res/js/Chart.js"></script>

Since you're creating the view content from your Servlet (a shoot on the foot, by the way), use request#getContextPath() to attach it:

"script src=\"" + request#getContextPath() + "/res/js/Chart.js\"></script>";
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

Rightly said by @VH-NZZ but in case you are using Spring 4x or above, you need to add static resources into ResourceHandlerRegistry. You can do this into your "AppConfig"(your application configuration file), like this :

@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan(basePackages = "com.packagename")
public class AppConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/build/**").addResourceLocations("/build/");
    registry.addResourceHandler("/dist/**").addResourceLocations("/dist/");
    registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    registry.addResourceHandler("/images/**").addResourceLocations("/images/");
}

Again as rightly said above, you should not keep your java files and static content together at the same location. These should always be available at a separate location. You can put your static content directly under your webapp folder.

Hemant Nagpal
  • 624
  • 6
  • 14