Search code examples
spring-bootthymeleaf

thymeleaf: Static resources are not loading in while using layouts


My directory structure is

Directory structure

src/
  main/
    resources/
        static/
             CSS/
             JS/
             images/

        template/
           fragments/
                         header.html
                         footer.html
                         navBar.html
            layouts/
                         appLayout.html
                         baseLayout.html
                 welcome.html

appLayout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
        <link rel="stylesheet" type="text/css" media="screen, projection" 
      href="/static/css/bootstrap.css" 
      th:href="@{/bootstrap.min.css}" />

  <link rel="stylesheet" type="text/css" media="screen, projection" 
      href="/static/css/bootstrap.css" 
      th:href="@{/css/bootstrap.min.css}" />


  <link rel="stylesheet" type="text/css" media="screen, projection" 
      href="/static/css/bootstrap.css" 
      th:href="@{css/bootstrap.min.css}" />


   <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap.min.css"
        th:href="@{/webjars/bootstrap/2.3.0/css/bootstrap.min.css}" rel="stylesheet" />


</head>
<body>

<div th:replace="/fragments/header :: header"></div>
<div th:replace="/fragments/navbar :: navbar"></div>
<div class="container">
    <div layout:fragment="content">
    <p>Content goes here...</p>
    </div>
    <footer>
    <div th:replace="/fragments/footer :: footer"></div>
    </footer>
</div>
</body>
</html>

Please do check the <links> tag in above layout, I have used different locations to the link tag, none giving the 404 error why is it so?

enter image description here

Please look the above image, I have css and js files in resources/static/css/ folder and JS is int /resources/static/js/ folder what is going wrong? why isn't chrome showing 404 error for some static resources?


Solution

  • The Bootstrap CSS and JS network requests are returning 200 because the response is successful, however the contents are not what you're expecting. If you look into the response you'll see that for every CSS and JS request, it is returning the HTML page welcome.html.

    This is because your Controller mapping is overriding the resource requests. You're using the name parameter for the mapping which isn't the correct attribute. Use value instead, e.g:

    @RequestMapping(value="/", method=RequestMethod.GET)
    

    This change will result in your CSS and JS requests returning 404's. This is progress.

    Also, remove your MvcConfig as this behavior is provided out of the box.

    Finally, adjust the path to your resources like this:

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

    Now the CSS and JS requests will return successfully with the appropriate content.