简体   繁体   English

Spring Boot服务静态资源

[英]Spring boot serving static resource

I work on spring boot application. 我致力于Spring Boot应用程序。 I'm trying to serve static content with spring. 我正在尝试使用Spring提供静态内容。 want to serve a resource stored in the /c:/frontend/files/ directory whenever a request comes in for the URL matching the pattern: /file/**: 希望在每次请求匹配以下格式的URL时提供服务在/ c:/ frontend / files /目录中存储的资源:/ file / **:

 @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry
            .addResourceHandler("/file/**")
            .addResourceLocations("file:///C:/frontend/files/" );

}

but when i try to access to this resource using this url: http://localhost:9999/file/app.min.js 但是当我尝试使用以下URL访问此资源时: http:// localhost:9999 / file / app.min.js

I have this problem 我有这个问题

There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation

I resolved the problem. 我解决了这个问题。 it's related to "spring-cloud-config-server". 它与“ spring-cloud-config-server”有关。 I just delete this config: org.springframework.cloud spring-cloud-config-server 我只是删除此配置:org.springframework.cloud spring-cloud-config-server

It sounds like your project's folder structure is wrong. 听起来您的项目的文件夹结构错误。

Code should go under src/main/java and resources (like your javascript) should go under src/main/resources . 代码应位于src/main/java ,资源(如您的JavaScript)应位于src/main/resources You have a few different options where you can actually serve the files from. 您有一些实际可以从中提供文件的选项。 This post on the spring.io blog has the following to say: spring.io博客上的这篇文章如下:

Spring Boot will automatically add static web resources located within any of the following directories: Spring Boot将自动添加位于以下任何目录中的静态Web资源:

  • /META-INF/resources/
  • /resources/
  • /static/
  • /public/

Another option you also have is using webjars . 您还可以选择使用webjars

Personally, I've found it easiest to put those kind of files under src/main/resources/public . 就个人而言,我发现将这类文件放在src/main/resources/public下是最容易的。 It always works without any issues for me. 对我来说,它始终没有任何问题。 The interesting thing is you can put a folder named /public anywhere in your project and spring-boot will serve files out of it. 有趣的是,您可以在项目中的任何位置放置一个名为/public的文件夹,而spring-boot将从中提供文件。 You have to be really careful that it's under src/main/resources/public though if you're using a build tool like maven, as when you come to build your .jar the files won't be in the right place otherwise. 您必须非常小心,它位于src/main/resources/public但是如果使用的是诸如maven之类的构建工具,则当您构建.jar时,文件将不在正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM