Accessing a web application's static resources

随声附和 提交于 2020-01-14 13:00:12

问题


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?


回答1:


The web-related resources should be placed in src/main/webapp




回答2:


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>&lt/wicket:link>



回答3:


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




回答4:


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.




回答5:


Spelling resources without the s?

reources/


来源:https://stackoverflow.com/questions/5473698/accessing-a-web-applications-static-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!