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.

https://i.sstatic.net/ehQvE.png

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

Is there a way to create an animation for changing .text in response to an on click event?

I'm currently developing a simple calculator that increases a variable when a button is clicked, displaying the updated value in a div. Each click on the 'amount-upwards' button adds 200 to the displayed number. Below is the jQuery code I a ...

Steps for transferring radiobutton value via ajax between two JSP pages:

(document).ready(function() { $("input[type='radio']").on("click", function() { var selectedRadioVal = $("input[name='price']:checked").val(); }); } I want to transfer the value of selectedRadioVal to a different jsp fi ...

H3 Tag Embraced by a Repetitive Image

As I'm developing a website, I've encountered an interesting challenge... I have an h3 tag that requires a repeating background on both sides. It's a bit difficult to describe, so I created this graphic to illustrate... Essentially, it&apo ...

Troubleshooting the error "System library was not found" in Eclipse Neon on Mac OS X when using Java 9

Can Java 9 be used as an Installed JRE in Eclipse on OS X (El Capitan 10.11.6)? I have installed both the Java 9 (EA build 165) JRE and JDK from the JDK Early Access Release page but I am encountering the following error in Eclipse Neon.3 (4.6.3) when I tr ...

Tips for maximizing algorithm efficiency in Java to identify prime numbers with 10 digits

I am relatively new to Java and programming in general. Currently, I am developing an algorithm to identify prime numbers within specific ranges. The algorithm currently handles six ranges for numbers under 1 billion. However, when attempting to determine ...

Unable to locate the element within the <figure> tag using Selenium Webdriver in Java

I am encountering an issue with my HTML source code in Selenium Webdriver. When I try to count the number of elements containing the text 'ABC' using a specific code snippet, it correctly returns 1. However, when I attempt to do the same for text ...

Exploring Protected Methods in Object Inheritance

Check out this fascinating code snippet: public class Superclass { public static void main (String[] args){ Superclass obj = new Subclass(); obj.doSomething(); #prints "from Superclass" } private void doSomething(){System.out.println( ...

Are the order of table rows retained by WebDriver findElements when retrieving them?

When you request an html table element list like the one below (e.g. using a tag): webDriver.findElement(By.id("mainTable")) .findElements(By.tag("tr")) Is there a specific order for the returned list? Can I assume that element[i] will always ap ...

Using jQuery to smoothly animate a sliding box horizontally

Is there a way to smoothly slide a div left and right using jQuery animation? I have been trying to achieve this by implementing the code below, which can be found in this fiddle. The issue I am facing is that every time I click on the left or right butto ...

After applying CSS, I am unable to click on the radio buttons

Even after selecting the other two, it still defaults to the first one. Here is my code: input[type=radio] { display:none; } input[type=radio] + label:before { content: ""; display: inline-block; ...

Xpath and cssselector are not very adaptable when dealing with ::before and ::after pseudoelements

HTML <li>::before<a href="#county" class="eods-error">::before"County is required."::after</a></li> After analyzing the above HTML code, I created the following locators: Cssselector : #eods-error > div > div.eods-error-box ...

What is the best way to animate the preprending of a div in an AJAX response?

Here is the code I am currently working with: $.ajax({ type: 'POST', url: 'load_more.php', data: {val:myval}, success: function (data) { $("#load_current").prepend(data); ...

Animating the background of a div element using jQuery

I am facing an issue with the code snippet below that I have written. It doesn't seem to be working as expected and I'm curious if anyone knows why. The problem is that I have set a background color on the DIV, but when hovering over it, I want ...

Evaluate a tooltip by hovering the mouse using the Selenium driver

As a newcomer to using Selenium for testing, I am facing an issue with testing tooltips on a pie chart. Here is the code I am working with: <g class="p0_tooltips"> <g id="p0_tooltip0" class="p0_tooltip" style="opacity: 0;" transform="translate(1 ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

Issue with Restful Web service - HTTP Status 404 - Unable to find the requested resource

When attempting to use a restful web service example, I encountered an HTTP Status 404 error stating that the requested resource is not available. Below are the details of my code. If you need any additional information, please let me know: Web.xml < ...

What is the best way to wrap all divs except for the one with a .header-container-wrapper class?

In the midst of a project involving hubspot, I am facing an issue. I need to enclose all div elements within the body tag, except those with the class .header-container-wrapper. The default code provided by hubspot wraps all divs within #site-wrapper. $(& ...

What is the best method for eliminating a character from all elements in jQuery classes?

I am working on an Angular 4 app where every .inner-page class in a html element includes a "/". For instance: <div _ngcontent-c0="" class="inner-page /login"> <div _ngcontent-c0="" class="inner-page /register"> I need to eliminate the "/" c ...

The secrets behind the seamless, fluid layout of this website

Upon exploring the website www.emblematiq.com, I noticed that it features a fluid/liquid layout. Despite analyzing the code, I am unable to decipher how this effect is achieved. The layout appears to be fixed width with the canvas element set at 1180px. D ...

Challenges arising from CSS position: fixed on iPhone 6+ in landscape orientation running iOS 9

Encountered a strange issue with the fixed header on my website under specific conditions: Using an iPhone 6+ in landscape mode. Using Safari with at least two tabs opened. The page has a fixed position header with html and body set to position: relative ...