Reputation: 1561
I have a Spring project where I included the following webjars into pom.xml
:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
Then I included in my HTML view the following link and scripts:
<link rel="stylesheet" href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
But it didn't work, no mapping found:
[org.springframework.web.servlet.PageNotFound] (default task-15) No mapping found for HTTP request with URI [/TestPublicWeb-0.0.1-SNAPSHOT/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css] in DispatcherServlet with name 'testapp'
...so I tried to include the following mapping into servlet.xml
:
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
But with this, mapping for my /TestApplication
is not found:
[org.springframework.web.servlet.PageNotFound] (default task-13) No mapping found for HTTP request with URI [/TestApplication/] in DispatcherServlet with name 'testapp'
How should webjars be included in a Spring project in a correct way?
Upvotes: 9
Views: 19110
Reputation: 12684
The problem is that you are mixing the standard HTML href
tag with Thymeleaf's syntax @{}
. Change it as follows:
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
And if you are using Spring Security you need also specify the authorization to your webjars in the configure(HttpSecurity http)
method like:
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
Upvotes: 23
Reputation: 2849
A couple things I could think of as to why the above is not working for you. Make sure you are using spring mvc namespace inside of your servlet.xml file. Looks something like:
<bean xmlns:mvc="http://www.springframework.org/schema/mvc"....
Also not sure why you are trying to access assets using @{..}
when you have specified the classpath. Try removing the @{..}
like so:
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
Upvotes: 3