I added the following dependencies to my Spring boot (using version 2.1.15) project:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.2.1</version>
</dependency>
On my Thymeleaf page I included the following CSS files and scripts:
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}">
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:src="@{/webjars/jquery/3.2.1/jquery.min.js}" type="text/javascript"></script>
To load the template, I defined the following controller mapping:
@RequestMapping(name = "/")
public String loadMainWeb() {
return "index";
}
However, when I run the application, the Bootstrap styles are not loading. I tested this by adding the btn and btn-primary classes to a button. Why are these styles not loading?
The full project can be found on GitHub.
The issue is your controller mapping. You're currently using the following mapping:
However, you used the
nameproperty in stead of thepathproperty on the@RequestMappingannotation. By leaving away thepathproperty, you actually tell Spring that you want to apply this controller mapping for all endpoints.That means that when you run the application, you're actually loading the
index.htmlpage when you're trying to load the WebJars files.To solve this, you should use
pathin stead ofname: