jqueryspringspring-bootwebjars

I am trying to use webjars in spring boot, but I get ERR_ABORTED 404


I tried to use Webjars to use jQuery in my spring boot project.

However, jQuery didn't work and I checked it by pressing F12.

GET http: // localhost: 8100 / webjars / jquery / 3.4.1 / jquery.min.js net :: ERR_ABORTED 404

First I added Webjars to pom.xml.

<dependencies>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery-ui</artifactId>
        <version>1.12.1</version>
    </dependency>   
    <!-- <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>webjars-locator</artifactId>
        <version>0.30</version>
    </dependency> -->
</dependencies>

And in the html header part I added:

<link rel="stylesheet" href="/webjars/jquery-ui/1.12.1/jquery-ui.min.css" />
<script type="text/javascript" src="/webjars/jquery-ui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="/webjars/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //alert("Hello~!?");
});
</script>

As you can see from the pom.xml code above, I tried using webjars-locator, but again I got the same error.

When I used webjars-locator I deleted the version name and used it.

What was the problem even though it was listed at https://www.webjars.org/documentation#springboot?


Solution

  • You need to tell spring where will be your js lib files.

    By default when you use webjars, all lib are added in webjars folder

    So you need to add this

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
              .addResourceHandler("/webjars/**")
              .addResourceLocations("/webjars/");
        }
    }
    

    or in XML

    <mvc:resources mapping="/webjars/**" location="/webjars/"/>
    

    And webjars-locator will find library on the classpath and use it to automatically resolve the version of any WebJars assets. This works for Spring ver >= 4.2

    Now you can use it in HTML like this

    <script src="/webjars/jquery/3.1.1/jquery.min.js"></script>