javaspring-bootthymeleafwebjars

Spring boot webjars: unable to load javascript library through webjar


I have a spring boot (I use Thymeleaf for templating) project where I want to use some jQuery libraries.

Unfortunately, the webjars aren't loading at all. I have tried many configuration but all of them failed.

Here is the code snippet of my HTML page:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">

<title>JAC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.js"
        th:src="@{/webjars/jquery/2.1.4/jquery.min.js}" type="text/javascript"></script>
<script src="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.js"  type="text/javascript"
        th:src="@{/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js}"></script>
<link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.5/css/bootstrap.min.css"
      th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}"
      rel="stylesheet" media="screen" />
<link href="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.css"
      rel="stylesheet" media="screen" />
</head>

I have added them in the pom file:

<dependency>
    <groupId>org.webjars.npm</groupId>
    <artifactId>jquery</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.3.5</version>
</dependency>

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery-file-upload</artifactId>
    <version>9.10.1</version>
</dependency>

But when calling the page I got a 404 on jquery.min.js and jquery.fileupload.min.js.

GET http://localhost:8888/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js 
2015-09-21 02:02:04.059 home:9 
GET http://localhost:8888/webjars/jquery/2.1.4/jquery.min.js 404 (Not Found)

Solution

  • You are referencing jquery library correctly. Maybe you are missing resource handler configuration.

    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
    

    Or if you use JavaConfig

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
      }
    
    }
    

    Webjars documentation

    If this will not work, please check if you have webjars on classpath (open your application JAR in 7Zip and check if webjars resources are inside it.)