'Spring Boot doesn't load javascript file

After Spring starts, I open my ajax.html page, but nothing happens. There is no error message, the js file just doesn't start. If I write javascript-code in ajax.html, it works normally.

ajax.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:c="http://xmlns.jcp.org/xml/ns/javaee">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript"
            src="webjars/jquery/2.2.4/jquery.min.js"></script>
    <script type="text/javascript" src="../static/js/main.js"></script>
</head>
<body>
<div id="fill">
</div>
</body>
</html>

project structure

enter image description here

enter image description here



Solution 1:[1]

I had the same issue, and solved it in the following way:

I added the addResourceHandlers to my Java config file:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

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

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

resources folder contains a static/js and a static/css folder both containing the specified files.

Hope it gives you help!

Solution 2:[2]

Have you added the resource handler for webjars? See: https://www.baeldung.com/maven-webjars

../static/js/main.js seems wrong. In spring boot, resources in the static directory are referred to without "static" in the URL, so just /js/main.js.

Other than that, are the scripts being loaded? What does the Network tab for the Console say?

Solution 3:[3]

As you are using Spring boot, you don't have to add "/static/**" folder in your url. You should miss "/static/" and write like this:

<script type="text/javascript" src="/js/main.js"></script>

And make sure that if you are using spring securiry, you should permit All to access "/js/**" path :

http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers( "/js/**", "/css/**")
        .permitAll()
        .anyRequest()
        .authenticated();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark
Solution 2 RoToRa
Solution 3 UdacianND004