我无法让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)


当前回答

将静态资源放在目录下:

/src/main/resources/static

在应用程序中添加此属性。属性文件

server.servlet.context-path=/pdx

您可以从http://localhost:8080/pdx/images/image.jpg访问

其他回答

你检查Spring Boot参考文档了吗?

默认情况下,Spring Boot将从类路径中的/static(或/public或/resources或/META-INF/resources)文件夹或ServletContext的根目录中提供静态内容。

您还可以将您的项目与Spring MVC服务Web内容指南进行比较,或者查看Spring -boot-sample- Web -ui项目的源代码。

有时候值得检查一下你是否用某个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,在这种情况下,您将不会收到静态内容。

如上所述,文件应该在$ClassPath/static/images/name.png, (/static or /public or /resources or /META-INF/resources)。这个$ClassPath表示main/resources或main/java目录。

如果你的文件不在标准dirs中,你可以添加以下配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/lib/**"); // like this
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // ... etc.
}
...

}

我认为前面的回答很好地解决了这个问题。然而,我要补充的是,当你在应用程序中启用了Spring Security时,你可能必须明确地告诉Spring允许对其他静态资源目录的请求,例如“/static/fonts”。

在我的情况下,我有“/static/css”,“/static/js”,“/static/images”默认允许,但/static/fonts/**被我的Spring安全实现阻塞。

下面是我如何解决这个问题的示例。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.....
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/fonts/**").permitAll().
        //other security configuration rules
    }
.....
}

与spring-boot的状态不同,要让我的spring-boot jar提供内容: 我必须通过这个配置类添加专门注册我的src/main/resources/static内容:

@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
            .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }
}