简体   繁体   中英

Accessing a web application's static resources

I've just built a very simple Java web application using the Wicked framework. The current layout of the project is:

src/
    main/
        java/
            net/myapp/
                Homepage.java
                Homepage.html
        reources/
            scripts/
                script.js

In the Homepage.html file I am trying to load the JavaScript file:

<script src="scripts/script.js"></script>

I deployed the application, but the browser doesn't find the JavaScript file.

The WAR file is being packaged using the maven-war-plugin. I looked into the WAR file, and I see the following layout:

WEB-INF/
    classes/
        net/myapp/
            Homepage.class
            Homepage.html
        scripts/
            script.js

What am I doing wrong? What am I missing?

与Web相关的资源应放在src/main/webapp

Your directory structure should be:

WEB-INF/
    classes/
        net/myapp/
            Homepage.class
            Homepage.html
        net/myapp/scripts/
            script.js

and your markup should be:

<wicket:link><script src="scripts/script.js"></script></wicket:link>

Resource sitting behind WEB-INF folder are not publicly available. If Homepage.class forwards to the Homepage.html, file you should be seeing that fine. But in the HTML page you have your reference to the javascript file, which is not publicly available. You need to move the scripts outside of the WEB-INF. The structure should look like

WEB-INF /
     classes /
     net/myapp/
          Homepage.class
          Homepage.html
scripts/
      scripts.js

This way a refernce in the html file to

<script src="scripts/script.js"></script>

will work properly. When the HTML page is rendered on the user side, they will make the call back to get the JavaScript resource. At this point, the file needs to be visible.

An update of your build script, or app layout should take care of this for you.

Edit: See Bozho's answer, it will fix the build for Maven. see This link for Maven

While the other answers are correct in general, they don't quite take Wicket into account. With Wicket, you can have resources on the classpath, and in some cases they are better than a static file.

You can use Application.mountSharedResource() to assign a url to a shared resource, which can come from anywhere, your classpath included.

没有s的拼写资源?

reources/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM