我无法让Spring-boot项目提供静态内容。

我在src/main/resources下放置了一个名为static的文件夹。其中有一个名为images的文件夹。当我将应用程序打包并运行时,它无法找到我放在该文件夹中的图像。

我试着把静态文件放在公共、资源和META-INF/资源中,但都不起作用。

如果我jar -tvf app.jar,我可以看到文件在jar的右边文件夹: /static/images/head.png为例,但调用:http://localhost:8080/images/head.png,我得到的是一个404

知道为什么弹簧靴找不到这个吗?(我使用1.1.4 BTW)


当前回答

适用于Thymeleaf,可以使用链接样式表

    <link th:href="@{/css/style.css}" rel="stylesheet" />

其他回答

配置方法如下:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcAutoConfigurationAdapter {

// specific project configuration

}

重要的是,您的WebMvcConfig可能会覆盖addResourceHandlers方法,因此您需要显式调用super.addResourceHandlers(注册表)(如果您对默认资源位置感到满意,则不需要覆盖任何方法)。

这里需要注释的另一件事是,那些默认的资源位置(/static、/public、/resources和/META-INF/resources)只有在还没有映射到/**的资源处理程序时才会被注册。

从现在开始,如果您在src/main/resources/static/images上有一个名为image.jpg的图像,例如,您可以使用以下URL访问它:http://localhost:8080/images/image.jpg(作为在端口8080上启动的服务器,应用程序部署到根上下文)。

有两件事需要考虑(Spring Boot v1.5.2.RELEASE)- 1)检查所有控制器类的@EnableWebMvc注释,如果有的话删除它 2)检查使用注释的Controller类- @RestController或@Controller。不要将Rest API和MVC行为混合在一个类中。对于MVC使用@Controller,对于REST API使用@RestController

以上两件事解决了我的问题。现在我的春季引导加载静态资源没有任何问题。 @Controller => load index.html =>加载静态文件。

@Controller
public class WelcomeController {

    // inject via application.properties
    @Value("${welcome.message:Hello}")
    private String message = "Hello World";

    @RequestMapping("/")
    public String home(Map<String, Object> model) {
        model.put("message", this.message);
        return "index";
    }

}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


    <link rel="stylesheet/less" th:href="@{/webapp/assets/theme.siberia.less}"/>

    <!-- The app's logic -->
    <script type="text/javascript" data-main="/webapp/app" th:src="@{/webapp/libs/require.js}"></script>
    <script type="text/javascript">
        require.config({
            paths: { text:"/webapp/libs/text" }
        });
    </script>



   <!-- Development only -->
     <script type="text/javascript" th:src="@{/webapp/libs/less.min.js}"></script>


</head>
<body>

</body>
</html>

2.使用弹簧启动器。*,我有一个控制器映射到路由GetMapping({"/{var}", "/{var1}/{var2}", "/{var1}/{var2}/{var3}"})和boom我的应用程序停止服务资源。

我知道这样的路线是不可取的,但这完全取决于你正在构建的应用程序(在我的情况下,我别无选择,只能有这样的路线)

所以这里是我的黑客,以确保我的应用程序再次提供资源。我只是有一个映射到资源的控制器。因为spring会先匹配一个直接路由,然后再匹配任何有变量的路由,所以我决定添加一个控制器方法,映射到/ images /{name},并对其他资源重复相同的方法

@GetMapping(value = "/images/{image}", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public @ResponseBody
    byte[] getImage(@PathVariable String image) {
        ClassPathResource file = new ClassPathResource("static/images/" + image);
        byte[] bytes;
        try {
            bytes = StreamUtils.copyToByteArray(file.getInputStream());
        } catch (IOException e) {
            throw new ResourceNotFoundException("file not found: " + image);
        }
        return bytes;
    }

这解决了我的问题

有时候值得检查一下你是否用某个rest控制器重写了全局映射。简单的例子错误(kotlin):

@RestController("/foo")
class TrainingController {

    @PostMapping
    fun bazz(@RequestBody newBody: CommandDto): CommandDto = return commandDto

}

在上面的例子中,当你请求静态资源时,你会得到:

{
    title: "Method Not Allowed",
    status: 405,
    detail: "Request method 'GET' not supported",
    path: "/index.html"
}

原因可能是你想要将@PostMapping映射到/foo,但忘记了@RestController级别上的@RequestMapping注释。在这种情况下,所有请求都映射到POST,在这种情况下,您将不会收到静态内容。

我也遇到了类似的问题,结果证明简单的解决方案是让我的配置类扩展WebMvcAutoConfiguration:

@Configuration
@EnableWebMvc
@ComponentScan
public class ServerConfiguration extends WebMvcAutoConfiguration{
}

我不需要任何其他代码来允许我的静态内容被服务,但是,我确实把一个名为src/main/webapp下的目录和配置maven指向src/main/webapp作为资源目录。这意味着public被复制到target/classes中,因此在运行时位于spring-boot/tomcat可以找到的类路径上。