具有上下文路径的Spring Boot静态内容 [英] Spring Boot static content with context path
问题描述
使用上下文路径时,我在Spring Boot中遇到静态内容问题.即:我希望将我的应用程序部署到localhost:8080/{appname}/
I'm having problems with static content in Spring Boot when using a context path. i.e.: I wish to deploy my app to localhost:8080/{appname}/
当我在没有上下文路径的情况下运行应用程序时,一切正常,Spring Boot会找到并运行我的.html
文件(来自资源/模板/,我正在使用Thymeleaf
)和JS文件(来自资源/static/js)/),但是当我使用以下任一方法添加上下文路径时:
When I run the app without context path everything works fine and Spring Boot finds and runs my .html
files (from resources/templates/, I'm using Thymeleaf
) and JS files (from resources/static/js/) but when I add the context path with either:
server.context-path=/{appname}
或
server.servlet-path=/{appname}
然后.html
页仍由JS文件显示,生成 404错误.
then the .html
pages are still displayed by the JS files generate 404 errors.
我尝试更改application.properties
中的spring.resources.static-locations
,并在我的MvcConfig.class
中覆盖了addResourceHandlers()
方法,但似乎都没有作用
I have tried to change the spring.resources.static-locations
in the application.properties
and overriding addResourceHandlers()
method in my MvcConfig.class
but neither seem to work
我使用一个MvcConfig
类,因为我需要定义一个CookieLocaleResolver
和一个MessageSource
,但这就是我在MvcConfig
中所拥有的全部.我不使用@EnableWebMvc
,而只是在@SpringBootApplication
注释中加上@ComponentScan
.
I use a MvcConfig
class because I need to define a CookieLocaleResolver
and a MessageSource
but that is all I have in the MvcConfig
. I do not use @EnableWebMvc
and just have the @SpringBootApplication
annotation with a @ComponentScan
.
任何帮助将不胜感激:)
Any help would be appreciated :)
推荐答案
根据您的评论:
HTML在没有应用上下文的情况下引用了JS
the HTML is referencing the JS without the app context
问题不在于Spring为js提供服务,其原因在于页面没有正确创建资源的URL.
the problem is not in Spring serving the js, its that the page is not creating the URL to the resources correctly.
Thymeleaf提供了一种机制,只需用th
前缀标记src属性即可自动支持此功能.
Thymeleaf provides a mechanism to support this automatically by just marking the src attribute with the th
prefix.
请参见第2节上下文相关的网址": www.thymeleaf.org/doc/article/standardurlsyntax.html
See section 2 "Context-relative URLs": www.thymeleaf.org/doc/articles/standardurlsyntax.html
这篇关于具有上下文路径的Spring Boot静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!