![](/img/trans.png)
[英]What is the correct base for relative URLs in Spring MVC application?
[英]Correct URLs in JavaScript files in Spring MVC
我不是Spring MVC的新手,但我總是想知道如何在JavaScript中使用正確的URL(知道上下文名稱)。 像c:url
或spring:url
,但對於JS:
例如,如果我有一個在Tomcat中部署為context
的webapp。 它有一個頁面: http://localhost:8080/context/some/directory/search
和API at http://localhost:8080/context/api
。 如果頁面調用API,我遇到問題:
// This works wrong:
$http.get('/api/users', function(data){}) // will call http://localhost:8080/api/users - the context is lost!
$http.get('api/users', function(data){}) // will call http://localhost:8080/context/some/directory/api/users - wrong URL!
我希望有一些過濾方式:
$http.get('${url:api/users}', function(data){}) // will call http://localhost:8080/context/api/users
我在C#和Ruby以及Python中看到了類似的東西。 是否有任何現成的Java / Spring解決方案?
正如@Vikdor的評論暗示的那樣,你必須讓你的服務器以某種方式處理JS文件。 我過去曾使用過這些方法:
使用解釋的頁面來提供資源。 只要您使用適當的@page
指令,JSP就非常樂意提供JS,JSON,CSS,HTML,PDF或任何其他Content-Type
。 然后,您可以像編寫HTML頁面一樣使用JSTL庫。 如果資源名稱是對你很重要,你必須要么寫一個控制器,用於解釋請求foo.css
由瀏覽投放foo.css.jsp
,或一些類似的翻譯。 此外,IDE會感到困惑,保佑他們,因此您可能必須覆蓋語法着色和自動完成才能充分利用這些功能。
編寫一個靜態內容過濾器來解析有趣令牌的資源(如${url}
),並在交付之前用適當的值替換它們。 它為資源交付增加了一些開銷,但對於我們的特定用例而言,其性能足夠高。
在其中任何一種情況下,請確保您記住應用程序使用適當的緩存標頭提供這些資源的能力,因此您的服務器不會執行額外的工作來提供重復的資源。
對於那些通過Google發現此問題的人,我將添加要點 :
<%@ page
language="java"
contentType="application/javascript; charset=UTF-8"
trimDirectiveWhitespaces="true"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/fragments/taglibs.jsp" %>
/**
* Returns servlet context aware URL, ready to use for AJAX calls and resource
* loading from JS.
*
* This script must be included before any other JS sources that want to use
* `url()`.
*
* @param {string}
* path a servlet context unaware path of URL, like `api/users`
* @returns {string} servlet context aware URL
* @author madhead
*/
function url(path){
return '<spring:url value="/" />' + path;
}
用法:
<script src="<spring:url value='/js/hsps/url.jsp' />"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.