我正在尝试使用Thymeleaf为我的Spring Boot项目添加bootstrap。
的index.html
<!DOCTYPE html >
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header"> </head>
<body>
<div th:replace="@{'views/' + ${content}} :: ${content}"></div>
<div lang="en" th:replace="fragments/footer :: footer"> </div>
</body>
</html>
footer.html
<div xmlns:th="http://www.thymeleaf.org" th:fragment="footer" >
<script th:src="@{/webjars/jquery/3.3.1/jquery.min.js}"></script>
<script th:src="@{/webjars/popper.js/1.12.9-1/umd/popper.min.js}"></script>
<script th:src="@{/webjars/bootstrap/4.0.0-1/js/bootstrap.min.js}" ></script>
</div>
了header.html
<head xmlns:th="http://www.thymeleaf.org" th:fragment="header" >
<meta charset="UTF-8">
<title>Модуль планирования ПД</title>
<link th:rel="stylesheet" th:href="@{webjars/bootstrap/4.0.0-1/css/bootstrap.min.css} "/>
</head>
MVC config.Java
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/")
.resourceChain(false);
}
}
样式不适用于页面和抛出错误:jazery,bootstrap,popper中的。
我怎么能解决这个问题?
谢谢。
为了更容易,我得到了webjars-locator:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0-2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
<version>0.30</version>
</dependency>
在我的页面,最后,我说:
<script th:src="@{/webjars/jquery/jquery.min.js}"></script>
<script th:src="@{/webjars/popper.js/umd/popper.min.js}"></script>
<script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
我没有在Spring启动中使用任何其他设置来使用。
如果你在你的pom.xml中使用org.webjars
依赖,那么你可能应该在/
之前添加斜杠webjars/...
并在header.html中保留属性rel="stylesheet"
:
<link rel="stylesheet" th:href="@{/webjars/bootstrap/4.0.0-1/css/bootstrap.min.css} "/>
还尝试在没有MvcConfig
配置类的情况下运行它。
使用Spring Boot,WebJars会自动配置。无需添加任何处理程序或其他配置。当您运行您的应用程序(没有任何配置),您可以看到这样的日志:
... Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
因此,删除您的MvcConfig
类可以解决问题。
事实上,我的Spring Boot应用程序与您的类似(但没有该配置文件)并且工作得很好。当我将配置添加到我的应用程序时,WebJars不再工作了!
您还可以通过以下方式添加webjars依赖项来解决此问题
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.0</version>
</dependency>
<!-- rest of needed dependecies -->
并将它们添加到模板标题中
<link rel="stylesheet" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}"/>
<script th:href="@{/webjars/jquery/3.4.0/jquery.min.js} "></script>
然后,如果运行Spring-Boot应用程序并查看页面源,则可以通过单击运行时的链接来访问此文件。