Bootstrap 3 styles not loading with Spring boot and WebJars

852 Views Asked by At

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.

1

There are 1 best solutions below

0
Dimitri Mestdagh On BEST ANSWER

The issue is your controller mapping. You're currently using the following mapping:

@RequestMapping(name = "/")
public String loadMainWeb() {
    return "index";
}

However, you used the name property in stead of the path property on the @RequestMapping annotation. By leaving away the path property, 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.html page when you're trying to load the WebJars files.

To solve this, you should use path in stead of name:

@RequestMapping(path = "/") // Use 'path'
public String loadMainWeb() {
    return "index";
}