Java Spring Boot 应用程序不提供静态内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29172612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:29:39  来源:igfitidea点击:

Spring Boot app not serving static content

javaspringspring-mvcconfigurationspring-boot

提问by John Douglas George

I am using Spring Boot, and am trying to make my static resources (CSS, JS, Fonts) available when deployed. The source code is available for you to look at or clone from https://github.com/joecracko/StaticResourceError.

我正在使用 Spring Boot,并试图在部署时使我的静态资源(CSS、JS、字体)可用。您可以从https://github.com/joecracko/StaticResourceError查看或克隆源代码。

Right now my CSS, JS, and Font files are not visible to my deployed website.

现在,我部署的网站看不到我的 CSS、JS 和字体文件。

Here is my project directory structure:

这是我的项目目录结构:

Here is my project directory structure

这是我的项目目录结构

Here is the root directory of the compiled JAR:I assure you the files are present in their respective folders.

这是编译后的 JAR 的根目录:我向您保证这些文件存在于它们各自的文件夹中。

enter image description here

在此处输入图片说明

Here is the network error I am seeing:

这是我看到的网络错误:

enter image description here

在此处输入图片说明

And here are my sources provided by chrome tools.Note that bar.css appears empty here. You may look at my source code to see that it is not empty.

这是我的 chrome 工具提供的资源。请注意 bar.css 在这里显示为空。你可以看看我的源代码,看它不是空的。

enter image description here

在此处输入图片说明

Here is my homepage.html

这是我的主页.html

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>

<!-- Main Styles -->
<link rel="stylesheet" href="/css/bar.css" />
<script src="/js/foo.js"></script>

</head>
<body>
    <div>Welcome to Foo!</div>
</body>
</html>

Here is my Web App Initializer(FooWebAppInitializer.java)

这是我的 Web App Initializer(FooWebAppInitializer.java)

public class FooWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ServletConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        //Spring Security
        container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
            .addMappingForUrlPatterns(null, false, "/*");

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcherServlet", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
        dispatcher.addMapping("*.css");
        dispatcher.addMapping("*.eot");
        dispatcher.addMapping("*.svg");
        dispatcher.addMapping("*.ttf");
        dispatcher.addMapping("*.woff");
        dispatcher.addMapping("*.map");
        dispatcher.addMapping("*.js");
        dispatcher.addMapping("*.ico");
    }
}

Here is my Servlet Configuration(ServletConfig.java)

这是我的 Servlet 配置(ServletConfig.java)

@Configuration
@EnableWebMvc
@ComponentScan({"com.foo"})
public class ServletConfig extends WebMvcAutoConfiguration{

    @Bean
    MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("messages");
        return source;
    }
}

And for kicks, My Spring Security Config(WebSecurityConfig.java)

另外,我的 Spring Security Config(WebSecurityConfig.java)

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**"); // #3
    }
}

采纳答案by Andrea

Put static resourcesunder the directory:

静态资源放在目录下:

/src/main/resources/static

You can also use publicor resourcesinstead of staticas folder name.

您也可以使用publicresources代替static作为文件夹名称。

Explanation: your build tool (Maven or Gradle) will copy all the content from /src/main/resources/in the application classpathand, as written in Spring Boot's docs, all the content from a directory called /static(or /publicor /resources) in the classpath will be served as static content.

说明:您的构建工具(Maven 或 Gradle)将复制/src/main/resources/应用程序类路径中的所有内容,并且如Spring Boot 的文档中所述,类路径中名为/static(or /publicor /resources)的目录中的所有内容将作为静态内容提供。



This directory could works also, but it is discouraged:

这个目录也可以工作,但不鼓励这样做:

/src/main/webapp/

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.

如果您的应用程序将被打包为 jar,请不要使用 src/main/webapp 目录。虽然这个目录是一个通用标准,但它只适用于 war 打包,如果你生成一个 jar,它会被大多数构建工具默默地忽略。

回答by gjp

There are 2 things to consider (Spring Boot v1.5.2.RELEASE)- 1) Check all Controller classes for @EnableWebMvc annotation, remove it if there is any 2) Check the Controller classes for which annotation is used - @RestController or @Controller. Do not mix Rest API and MVC behaviour in one class. For MVC use @Controller and for REST API use @RestController

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

Doing above 2 things resolved my issue. Now my spring boot is loading static resources with out any issues. @Controller => load index.html => loads static files.

做以上两件事解决了我的问题。现在我的 Spring Boot 正在加载静态资源,没有任何问题。@Controller => 加载 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

索引.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</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>