Spring Boot WAR 部署到 Tomcat 后静态资源缺失上下文路径

3
我在将Spring Boot应用程序部署为WAR文件到独立的Tomcat 7服务器时遇到了问题。它可以构建和部署,但当index.html页面尝试加载其他静态资源时,它们缺少url中的上下文,因此无法加载(404)。
例如: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

我已尝试过的事情:

  • 在application.properties中设置contextPath,但这仅适用于嵌入式Tomcat
  • 尝试使用全新安装的Tomcat 7
  • 尝试创建一个配置文件在Tomcat中强制上下文: apache-tomcat-7.0.72\conf\Catalina\localhost\spring-boot-war-context-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的答案是完美的解决方案!

我仍然在WebSphere 8.5服务器上遇到这个问题。 - Tamer Awad
2个回答

3

这不是由于您在 index.html 中定义的 URL 的方式引起的吗(URL 不包括 context root):

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

使用相对路径

您应该能够使用相对路径(不带前导斜杠):

<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);

Alex,感谢您详细的回复,解释了很多问题。我尝试将页面从HTML转换为JSP页面,并使用上述方法,在本地运行良好,但在Tomcat服务器上出现错误——很可能只是一些配置问题。话虽如此,我们计划开发一个Angular应用程序,因此不认为JSP是一个选项。考虑到每个链接需要多少额外的代码行,我不确定纯JavaScript选项是否可行。也许最好将应用程序放在Tomcat的根目录中,或者这是不好的做法? - James
你也可以使用相对路径:<img src="app/images/springboot.png" />。我已将其添加到答案中。将路径设置为相对于你的HTML页面。 - alexbt
就是这样!非常感谢你的帮助 - 你真是个传奇。 - James

0
如果使用Thymeleaf,另一种方法是使用类似下面的上下文相关URL:
<link rel="icon" type="image" th:href="@{/img/favicon.ico}"/>

更多信息请参考:Thymeleaf文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接