Guidance on incorporating static files with Spring MVC and Thymeleaf

I'm seeking guidance on how to properly incorporate static files such as CSS and images in my Spring MVC application using Thymeleaf. Despite researching extensively on this topic, I have not found a solution that works for me. Based on the recommendations from various sources, I placed my CSS and image files in the resources/static/css and resources/static/images directories.

All my HTML files, which require these CSS and image files, are located under templates within the webapp/WEB-INF/templates directory.

In my LoginApplicationConfig file, I added the following two methods at the bottom to enable the use of styles and images in my HTML files:

@EnableWebMvc
@Configuration
@ComponentScan({ "com.myapp.spring.*" })
@Import(value = { LoginSecurityConfig.class })
public class LoginApplicationConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    // Other methods here...

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/css").setCachePeriod(31556926);
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/images").setCachePeriod(31556926);
    }
    
    // Other methods here...

}

To include the style file in my index.html file using Thymeleaf, I added the following line:

<link rel="stylesheet" th:href="@{css/stylesmd.css}" type="text/css">

However, I continue to encounter an error stating that the stylesmd.css file failed to load.

My queries are:

  1. Have I placed my styles and image files correctly? Specifically, where should I place them within my project structure?
  2. Are the additional methods in LoginApplicationConfig necessary? Furthermore, I am unsure about what to include in addResourceHandler(...) versus addResourceLocations(...).
  3. Is my reference to the stylesheet (using Thymeleaf) accurate?

Despite the abundance of information available on this issue, none of it has been effective in solving my problem. Hence, I am reaching out for assistance.

Answer №1

Here is the solution that worked for me in just one line:

registry.addResourceHandler("/static/**").addResourceLocations("/static/");

Additionally, ensure to include this code snippet in your HTML file:

<head>
    <link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="@{/static/css/your.css}"/>
</head>

If you are still encountering issues, consider relocating your "templates" folder as a subfolder within the resources directory.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to convert a String containing multiple JSON blobs into a List of Strings using Jackson?

I am trying to convert a String containing concatenated JSON objects with varying structures into a list of strings. For example, given the following input: { "foo": "bar" }{ "wibble": "wobble" } I want the output to be a List<String> object th ...

What is the best way to create a 6-column grid system without using bootstrap?

I am looking to create a row with 2 columns that should turn into 2 separate rows, each containing one column when viewed on smaller devices. I have researched CSS Grid but find it quite complex. Can someone simplify it for me? Thank you! ...

The result of the parsing with SimpleDateFormat is null

I have a time stamp in the format "2013-03-28T15:16:58.000Z" and I need to convert it to "dd-MMM-yyyy" format. To achieve this, I wrote the following code: public static String getTime(String time) { try { String tim = time.rep ...

Utilize the div element to segment a webpage into four different sections

Within a div tag, I have used 4 other div tags to create equal areas. Is there an alternative method to achieve this division or improve it? <div style="width: 689px; margin-left: 215px; margin-top: 0px; float: none; height: 502px;"> ...

The toggle feature of the Bootstrap responsive navbar is not functioning properly

I am currently implementing Twitter Bootstrap in a Rails project, but I'm encountering issues with the responsive navbar. When I resize the screen, the menu toggle button appears along with the navbar options open below it. Upon further shrinking, the ...

Using Jquery to set values for css properties

I've recently started using jquery and I have a task related to a drop-down menu that I'm struggling with: if (scrnwidth <= 761) { if (display was block) { //Defaultly testi has display:none property. testi = m ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Attempting to align a FieldSet in the middle of the page

Having trouble aligning a field set within a div. The first two elements are centered right next to each other, but the third one is justified left and I'm struggling to center it within the div. JSP <tr> <th> <span onclick="toggleDiv ...

Tips for displaying a background image without obstructing the container class on your website

How can I set a background image for my website? Whenever I use the code background-image:url('path_to_image');, it ends up covering my container class. Is there a way to place the image behind the container class? ...

The CSS linear gradients rainbow wheel is missing a few sections, only displaying part of its 12

I've almost got everything working, but I'm facing a challenge in displaying all 12 sections of the rainbow wheel. I know it's probably something very simple (Occam's razor). I've been following this amazing tutorial on CSS linear ...

Utilizing Angular 2+ with the [innerHTML] property to incorporate HTML with added style attributes

I am currently utilizing Angular 2+ [innerHTML] input for inserting HTML formatting that includes style tags. Within my template, the code looks like this: <span [innerHTML]="someVar"></span> In the component file, I have defined: someVar = ...

Issues with 'floating' unordered lists

.menu li { float: left; color: #fff; font-weight: bold; } .menu li a { display: block; height: 20px; min-width: 110px; text-decoration: none; border-radius: 3px; padding: 4px; padding-left: 6px; padding-right: 6p ...

Toggle between list elements using the inner text of the elements with jQuery

My issue lies in figuring out why my filter function isn't properly working for toggling li elements. JavaScript: $("#searchbox1").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#menulist li") ...

What is the best way to adjust inline svg to the user viewport size?

After working on integrating my interactive SVG maps into my HTML pages, I encountered a minor issue: when inserting my inline SVG into a standard, non-responsive HTML document, it automatically adjusts itself to fit nicely within the user's viewport. ...

When using Selenium, ensure that tests are gracefully aborted in the event of a catastrophic error, while still generating a detailed test

After searching through existing questions and answers on this topic, I have not found any that directly address my question at hand. In my test automation setup, I am utilizing two listeners - TestListener and CustomReportListener - along with the TestNG ...

Various modules in the project need to have distinct GitHub origins, particularly in the case of Spring-Angular

My goal is to create a well-structured project with separate frontend and backend modules. Here is the initial project structure: https://i.stack.imgur.com/EghPA.png I have attempted this in various configurations before, but every time I try, git recogn ...

Using Java's JsonPath library to insert an object into another object

Currently utilizing the JayWay JsonPath library for JSON object manipulation. In need of inserting a JSON object into an existing JSON array: ### before { "students": [] } ### after { "students": [{"id": 1, "name&qu ...

Display exclusively the provided value

Can someone please help me with printing in PDF style and displaying only the inputted value without showing the textbox or dropdown? Check out this image for reference I would like to achieve something similar, how can I do that? Any assistance would be ...