簡體   English   中英

如果我在Jersey的@Path注釋中使用子資源,則找不到JavaScript文件

[英]JavaScript file not found if I use sub-resource in Jersey's @Path annotation

我有一個Jersey REST Web服務,這是URL路徑http://localhost:8080/myapp/account/home資源類。

@Path("account/home")
public class AccountResources {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable displayForm() {
        return new Viewable("/homepage.html");
    }
}

HTML文件homepage.html與一個JavaScript文件鏈接,該文件應從服務器上的js/jump.js加載:

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

但是,當我啟動Webapp並打開http://localhost:8080/myapp/account/home (基本上是homepage.html )時,未加載JavaScript文件js/jump.js 因此,我必須添加上下文根路徑/myapp/才能使其工作:

<script src="/myapp/js/jump.js"></script>

這不是很漂亮,因為上下文根路徑/myapp可以在以后更改。 因此,我不想在我的HTML文件中的任何地方添加/myapp 另外,我的webapp中的物理目錄布局如下:

WebContent
    |
    |_____ homepage.html
    |
    |_____ js
            |
            |____ jump.js

因此,即使實際上js/jump.jshomepage.html在相同的Web根目錄中,即使我在homepage.html使用<script src="js/jump.js"></script> ,為什么它不起作用服務器? 如果我以這種方式使用@Path注釋,Jersey servlet是否會更改HTML和JavaScript文件的相對URL路徑? 我嘗試了使用@Path而不使用子資源的另一種方式:

@Path("account")

這次,我可以在homepage.html使用<script src="js/jump.js"></script> ,如果打開http://localhost:8080/myapp/account則可以成功加載JS文件。 因此,似乎在Jersey的@Path("account/home")批注中定義的URL路徑中的子資源將使JavaScript相對文件路徑不可搜索。

有什么好辦法可以讓雙方都開心嗎? (即,我可以在URL路徑中使用兩個子資源,例如@Path("account/home")而無需將js/jump.js更改為/myapp/js/jump.js

嘗試寫作

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

在第一個示例中,服務器評估到http://localhost:8080/myapp/account/js/jump.js的相對路徑

但您需要的是:

http://localhost:8080/myapp/js/jump.js

因此,只要讓瀏覽器知道查找一個路徑即可。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM