Spring Boot app not serving static content

后端 未结 2 503
悲&欢浪女
悲&欢浪女 2020-12-31 17:07

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 htt

相关标签:
2条回答
  • 2020-12-31 17:45

    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

    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.

    @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>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>
    
    0 讨论(0)
  • 2020-12-31 18:06

    Put static resources under the directory:

    /src/main/resources/static
    

    You can also use public or resources instead of static as folder name.

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


    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.

    0 讨论(0)
提交回复
热议问题