Spring boot webjars: unable to load javascript library through webjar

僤鯓⒐⒋嵵緔 提交于 2019-12-03 03:03:17

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.)

After inspecting the webjar for jquery, I got this working by adding a "dist" subpath.

<script src="webjars/jquery/2.1.4/dist/jquery.min.js" type="text/javascript"></script>

The webjars dependencies should be available on the spring boot classpath, so you should try referencing the webjars using the src attribute like so:

<script src="webjars/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js"></script>
<link href="webjars/bootstrap/3.3.5/css/bootstrap.min.css"
  rel="stylesheet" media="screen" />
<link href="webjars/jquery-file-upload/9.10.1/jquery.fileupload.css"
  rel="stylesheet" media="screen" />

I ended up doing a mvn clean install (from cmd prompt) to get the target cleaned and all the lib/jars populated correctly. I am using Spring boot with Intelij.

Additional answer found on one blog:

When using Spring Framework version 4.2 or higher, it will automatically detect the webjars-locator library on the classpath and use it to automatically resolve the version of any WebJars assets.

In order to enable this feature, we’ll add the webjars-locator library as a dependency of the application:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.30</version>
</dependency>

In this case, we can reference the WebJars assets without using the version; (...)

if you use servlet 3.x just add :

1- using java config :

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

            registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/").resourceChain(false);

       registry.setOrder(1);
    }


}

2- or xml config :

<mvc:resources mapping="/webjars/**" location="/webjars/"> 
  <mvc:resource-chain resource-cache="false" /> 
</mvc:resources>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!