Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

549
Views
Load static resource in Spring Boot with Thymeleaf

I want to make page using thymeleaf. But I have some problem with the static files. I've investigated questions(1,2,3) with similar problem, but it didn't help me.

I use Spring Boot framework in the application. My files look like: enter image description here

test.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script src="js/test.js" th:src="@{/test.js}"/>
</head>
<body>
<button onclick="testFunction('test value')">Button</button>
</body>
</html>

test.js

function testFunction(test) {
    console.log(test);
}

Configuration class

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
        super.addResourceHandlers(registry);
    }
}

And problem, when I load test.html file with javascript not loaded.

@GetMapping(value = "web/test")
public String getTestHtmlPage() {
    return "test";
}

enter image description here

/api/v1 is a configuration in application.properties => server.servlet-path=/api/v1

What do I do wrong? Can you help me?

Thanks all!

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

For a better understanding of registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");

I wrote a more thorough answer here that discusses invalid resource location mappings. It didn't receive any upvotes, so I hope it's not terrible. :-)

In short, with the way you're mapping classpath:/static/js/, and then accessing, /js/test.js, you're telling Spring to look in /static/js/js/test.js.

What you probably want is classpath:/static/. In that case, when you try to access /js/test.js, it's looking in /static/js/test.js for the file instead.

As for Thymeleaf, I've never used it, but docs indicate you should load scripts with th:src instead of th:href. th:href appears to only be for HTML content.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!