将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 \卡塔利娜\本地主机\ spring 引导战争上下文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日:
亚历克斯在下面的回答是关于在开始时使用没有斜线的相对URL是完美的解决方案!
1 回答
是不是仅仅由您在
index.html
中定义网址的方式引起的(网址不包含context root
):使用相对uri
你应该能够使用相对uri(没有前导斜杠):
获取上下文根
How do you get the contextPath from JavaScript, the right way?
How to set ContextPath for an image link
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
How to use relative paths without including the context root name?
使用JSP / JSTL:
或者使用Javascript: