Static resources in Spring not working. Any ideas?

1.8k views Asked by At

Situation:

I have a fresh spring project from start.spring.io
And I have created the file project/src/main/resources/js/a.js

I have created also project/src/main/resources/templates/index.html (it's with thymeleaf) that needs that a.js by <script th:src="@{/js/a.js}"></script>

I also have the following configuration:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/js/**")
                .addResourceLocations("/js/");

    }
}  

When the app is starting I can see in the logs:
Mapped URL path [/js/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Tried:

  1. At the .addResourceLocations(); I have tried all kind of variants like: "/resources/js", "resources/js", "/js", "js"
  2. Also in application.properties used spring.resources.static-locations=classpath:/resources/
  3. create /resources/static/js/a.js and update the addResourceLocatios parameter accordingly

Any ideas?

1

There are 1 answers

1
Ajit Soman On BEST ANSWER

You will need to place a.js file inside static folder. I have attached folder structure below:

enter image description here

Also remove your MvcConfig since it is not required.