我正在尝试使用此处的信息在 spring-boot服务器中添加静态Web内容
我尝试在上一个链接所说的几个文件夹中添加我需要的.js和.css文件,但它不起作用:
Run Code Online (Sandbox Code Playgroud)/META-INF/resources/ /resources/
注意:我没有创建/static/
和/public/
文件夹,因为我不知道项目中的绝对路径.
我也添加了addResourceHandlers
方法:
Run Code Online (Sandbox Code Playgroud)@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!registry.hasMappingForPattern("/webjars/**")) { registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); } if (!registry.hasMappingForPattern("/**")) { registry.addResourceHandler("/**").addResourceLocations( RESOURCE_LOCATIONS); } }
HTML文件中的引用如下所示:
<script src="bootstrap-switch.js"></script>
知道如何解决这个问题吗?
更新:
更新2:尝试@jfcorugedo
不起作用.看一下,那是你在说什么?
更新3:尝试@jfcorugedo,第二个建议:
Dan*_*mes 20
我认为你应该使用访问静态内容 mydomain/<context>/<resource type>/resource
例如:
http://mydomain/app/js/test.js
http://mydomain/app/img/test.jpg
Run Code Online (Sandbox Code Playgroud)
您可以使用应用程序上下文或仅使用相对路径编写资源:
<script src="js/bootstrap-switch.js"></script>
Run Code Online (Sandbox Code Playgroud)
要么
<script src="/<myapp>/js/bootstrap-switch.js"></script>
Run Code Online (Sandbox Code Playgroud)
但是,如果你使用带有webjar的bootstrap,你应该写
<script src="/<myapp>/webjars/bootstrap/<version>/js/bootstrap-switch.js"></script>
Run Code Online (Sandbox Code Playgroud)
github上有一个项目来说明这个 https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-static
更新1
我创建了一个具有以下结构的测试项目:
我可以在http:// localhost:8080/css/style.css上访问style.css
您可以使用http://start.spring.io/来帮助您创建新项目
另一种选择是使用Spring Tool Suite或IntelliJ IDEA.他们可以帮助您使用正确的配置创建新项目(如上一个链接).
jfc*_*edo 16
您不需要添加方法addResourceHandlers,Spring启动会在自己的代码中执行此方法.
不要将文件放在webapp文件夹中.
您只需将文件放在以下目录之一:
/META-INF/resources/
/resources/
/static
/public
例如,如果要加载文件js/bootstrap-switch.js
,则此文件必须位于以下文件夹之一:
/META-INF/resources/js/bootstrap-switch.js
/resources/js/bootstrap-switch.js
...
我在/ src/main/resources中创建了一个文件夹META-INF/resources/js,一切正常:
我在这个文件夹中放了一个test.js文件,当我输入URL http:// localhost:8080/js/test.js时,应用程序给了我JS文件.
您确定要创建相同的文件夹层次结构吗?
看一org.springframework.boot.autoconfigure.web.ResourceProperties
下课,你可以看到这行代码:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
Run Code Online (Sandbox Code Playgroud)
这意味着/META-INF/resources/
,/resources/
,static/
和public/
目录都可以提供静态内容.
因此,您可以在目录下创建一个static/
或目录,并将静态内容放在那里.它们将通过以下方式访问:.(假设是8080)public/
resources/
http://localhost:8080/your-file.ext
server.port
您可以spring.resources.static-locations
在中使用自定义这些目录application.properties
.
例如,通过提供此配置:
spring.resources.static-locations=classpath:/custom/
Run Code Online (Sandbox Code Playgroud)
您可以使用下面的custom/
文件夹resources/
来提供静态文件,并通过上面的URL访问它们.
归档时间: |
|
查看次数: |
77928 次 |
最近记录: |