Spring引导WAR部署到Tomcat并缺少静态资源的上下文

时间:2016-10-23 13:46:30

标签: java spring tomcat spring-boot

将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

Image showing issue

使用嵌入式Tomcat时工作正常

类似问题:

似乎是一个类似的问题: Spring-Boot war external Tomcat context path

然而,该问题的建议似乎并未解决我的问题。我不确定Tomcat xml文件。

遵循的步骤:

我创建了一个简单的示例应用程序,并按照Spring Boot文档中的步骤进行操作。

可以在此github存储库中看到示例代码以及重现问题的步骤:https://github.com/jgraham0325/spring-boot-war-context-issue

到目前为止我尝试过的事情:

  • 在application.properties中设置contextPath,但这仅适用于嵌入式tomcat
  • 尝试使用全新安装的Tomcat 7
  • 尝试在tomcat中创建配置文件以强制上下文: Apache的Tomcat的7.0.72 \ CONF \卡塔利娜\本地主机\弹簧引导战争上下文issue.xml

spring-boot-war-context-issue.xml的内容:

    <Context 
    docBase="spring-boot-war-context-issue" 
    path="spring-boot-war-context-issue" 
    reloadable="true" 
    />

非常感谢任何建议!

由于

2016年10月23日更新:

下面回答Alex关于在开始时没有使用斜杠的相对URL的答案是完美的解决方案!

2 个答案:

答案 0 :(得分:1)

这不仅仅是由于您在index.html中定义网址的方式造成的(网址不包含context root):

<img src="/app/images/springboot.png" />

使用相对uri

你应该可以使用相对uri(没有前导斜杠):

<img src="app/images/springboot.png" />

获取上下文根

使用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