【发布时间】:2014-07-10 10:30:42
【问题描述】:
我对 Spring MVC 并不陌生,但总是想知道如何在 JavaScript 中使用正确的 URL(上下文名称感知)。 c:url 或 spring:url 之类的东西,但对于 JS:
例如如果我有一个在 Tomcat 中部署为 context 的 web 应用程序。它有一个页面:http://localhost:8080/context/some/directory/search 和http://localhost:8080/context/api 的 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 有没有现成的解决方案?
【问题讨论】:
-
您可能应该将上下文名称(使用ServletContext#getServletContextName())放入您的javascript命名空间。您可以通过在加载 javascript 的 html 文件中包含
<script>来执行此操作。然后你可以用这个上下文形成 URL。顺便说一句,你是如何在 C#/Ruby/Python 中做到这一点的? -
我不确定,但我在 Ruby 中看到了类似
@url或:url的内容。我知道问题是默认 servlet 不过滤 JS,并且在 Ruby JS 中是动态服务的,但我希望存在一些美丽的方式。
标签: java javascript spring spring-mvc servlets