Stefano Pisano
Stefano Pisano

Reputation: 438

Spring doesn't load custom css

I have a problem with my spring boot application. It seems that it doesn't load the custom css file. I put it under resources/static/css, I also tried under resources/public/css but it doesn't work too.

I leave you my project on git hub account so you can check what is wrong

GitHub Project

Also, when I open the login page under the console of chrome there is a warning

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:8080/css/style.css".

Upvotes: 2

Views: 2103

Answers (2)

Abacus
Abacus

Reputation: 19421

The problem lies in your MonthlyExpensesController which contains the following code:

@RestController("/monthly")
public class MonthlyExpensesController {

    @GetMapping()
    public Expenses getMonthlyExpenses() {
        return null;
    }
}

Your error is that you try to set the path /monthly for the controller with the value of the annotation. But the value of the @RestController annotation ist used as a bean name and not for path resolution.

Therefore your MonthlyExpensesController is registered for the default path. It is found as a controller to handle /css/style.css and returns null which results in the empty response you see.

Change the controller to:

@RestController
public class MonthlyExpensesController {

    @GetMapping("/monthly")
    public Expenses getMonthlyExpenses() {
        return null;
    }
}

and it works as it should.

One more thing: Please in future use minimal, compilable examples, I first had to setup a dummy database to get the program running.

Update:

Besides changing the controller so that the css file will be served, you need to fix the code to load the stylesheet. You have to change

<link type ="text/css" href="css/style.css"/>

to

<link rel="stylesheet" href="css/style.css"/>

otherwise the file is not interpreted as a css file. The login page then looks like this when I run it:

login screen

Personally, I would move the lines loading the css files from the end of the page into the <head> section, that prevents the unstyled page being displayed until the css are loaded.

Upvotes: 2

Sangam Belose
Sangam Belose

Reputation: 4506

Try this. since you are using Thymeleaf you can use that to fetch the resource.

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

Upvotes: 0

Related Questions