将Spring Boot应用程序作为WAR文件部署到独立的Tomcat 7服务器时遇到问题。它构建和部署很好,但是当index.html页面试图加载其他静态资源时,它们会丢失url中的上下文,因此无法加载(404)。
e.g。 http://localhost:8080/app/images/springboot.png
应该是:http://localhost:8080/spring-boot-war-context-issue/app/images/springboot.png
使用嵌入式Tomcat时工作正常
似乎是一个类似的问题: Spring-Boot war external Tomcat context path
然而,该问题的建议似乎并未解决我的问题。我不确定Tomcat xml文件。
我创建了一个简单的示例应用程序,并按照Spring Boot文档中的步骤进行操作。
可以在此github存储库中看到示例代码以及重现问题的步骤:https://github.com/jgraham0325/spring-boot-war-context-issue
spring-boot-war-context-issue.xml的内容:
<Context
docBase="spring-boot-war-context-issue"
path="spring-boot-war-context-issue"
reloadable="true"
/>
非常感谢任何建议!
由于
答案 0 :(得分:1)
这不仅仅是由于您在index.html
中定义网址的方式造成的(网址不包含context root
):
<img src="/app/images/springboot.png" />
你应该可以使用相对uri(没有前导斜杠):
<img src="app/images/springboot.png" />
How do you get the contextPath from JavaScript, the right way?
How to use relative paths without including the context root name?
使用JSP / JSTL:
<img src="${pageContext.request.contextPath}/app/images/springboot.png" />
或使用Javascript:
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
...
var img = new Image();
img.src = getContextPath() + "/app/images/springboot.png";
document.getElementById('div').appendChild(img);
答案 1 :(得分:0)
如果使用Thymeleaf
,则另一种方式是使用Context-Relative URLs
,如下所示:
<link rel="icon" type="image" th:href="@{/img/favicon.ico}"/>
有关更多信息,请参阅:Thymeleaf Documentation