【问题标题】:The Spring Boot application can not find the webjar fileSpring Boot 应用程序找不到 webjar 文件
【发布时间】:2018-07-06 00:38:29
【问题描述】:
【问题讨论】:
标签:
java
spring
spring-mvc
spring-boot
gradle
【解决方案1】:
假设您使用的是 maven。在你的 pom.xml 添加
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
<scope>runtime</scope>
</dependency>
然后在您的 html 文件中,这就是您应该如何引用 webjar 的方式
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7/css/bootstrap.css">
确保您的依赖 groupId 来自“org.webjars”
【解决方案2】:
我遇到了和你一样的问题。所以经过一番研究,我发现 WebJars 与 Spring 无关,所以我们必须使用 Spring MVC 为这些客户端依赖项定义一些映射。
假设你的 pom.xml 中有这个依赖:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>
所以尝试将此配置添加到您的项目中,我认为它会起作用。
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/");
}
}
然后在您的 HTML 中引用您的代码:
<link rel="stylesheet" href="/webjars/bootstrap/4.3.1/css/bootstrap.css">
或在你的百里香中更好:
<link th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}" rel="stylesheet" />
【解决方案3】:
如果使用 Spring Boot 2 的其他人看到这一点 - 使用 Spring Security,我遇到了同样的问题并且不得不进行一些更改:
在实现WebMvcConfigurer的配置类中删除了@EnableWebMvc,以便使用@SpringBootApplication注释的主类可以自动配置
-
在与上述相同的配置类中,覆盖addResourceHandlers() 方法:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").resourceChain(false);
}
-
在扩展 WebSecurityConfigurerAdapter 的 Spring Security 配置类中,我必须做一些事情:
一个。让 Spring 通过删除 @EnableWebSecurity 来自动配置安全性
b.覆盖configure(HttpSecurity http) 方法,就像您可能已经在做的那样,添加蚂蚁匹配器以允许/webjars/**
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/webjars/**").permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
c。覆盖configure(WebSecurity webSecurity) 方法:
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers("/webjars/**");
}