Bootstrap 4 webjar css не работает с Spring Boot + Thymeleaf

Я делаю веб-приложение Spring Boot, используя Thymeleaf. Я экспериментировал с Webjars, чтобы использовать на своей веб-странице такие вещи, как JQuery и Bootstrap. Использование Spring Boot 2.2.6.RELEASE и попытка использования Bootstrap Webjar версии 4.1.1-1.

У меня есть несколько разных веб-файлов в моем pom, но я понял, что ни один из файлов css не загружается. Файлы Javascript из веб-файлов загружаются нормально, но ни один из css не применяется. При просмотре инструмента отладчика веб-разработчика я вижу, что все файлы Javascript есть, но ни один из файлов css отсутствует.

В настоящее время я специально пытаюсь заставить работать вкладки Bootstrap, но очевидно, что без каких-либо стилей Bootstrap ни одна из функций Bootstrap не будет работать.

Вот как выглядит мой контроллер:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController {

  @RequestMapping(value = "/stats", method = {RequestMethod.GET, RequestMethod.POST})
  public String stats(
      Model model) {

    // some code adding simple attributes to the model

    return "stats";
  }
}

У меня есть этот класс веб-конфигурации:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/")
        .resourceChain(false);
  }
}

Образец моего помпона:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <!-- artifact info... -->

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

    <!-- some other dependencies -->

    <!-- Webjars -->
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>4.4.1-1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap-datepicker</artifactId>
      <version>1.7.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.5.0</version>
    </dependency>

    <dependency>
      <groupId>org.webjars.npm</groupId>
      <artifactId>popper.js</artifactId>
      <version>1.16.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>font-awesome</artifactId>
      <version>5.13.0</version>
    </dependency>

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

    <!-- Spring -->

    <!-- some other Spring deps... -->

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Вот пример моей html-страницы (stats.html):

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8"/>
  <title>My Web App</title>

  <link th:rel="stylesheet" th:href="@{webjars/bootstrap/css/bootstrap.min.css}" type="text.css"/>
  <!--<link th:rel="stylesheet" th:href="@{webjars/bootstrap-datepicker/css/bootstrap-datepicker.min.css}" type="text/css"/>-->
  <link th:rel="stylesheet" th:href="@{webjars/bootstrap-datepicker/css/bootstrap-datepicker.standalone.css}" type="text/css"/>
  <link th:rel="stylesheet" th:href="@{webjars/font-awesome/css/all.css} " type="text/css"/>
  <link href="../static/css/custom-styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
  <script th:src="@{webjars/jquery/jquery.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/popper.js/1.14.3/umd/popper.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/bootstrap/js/bootstrap.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/bootstrap-datepicker/js/bootstrap-datepicker.min.js}" type="text/javascript"></script>

  <!-- Other simple web content... -->

  <!-- Example straight from Bootstrap 4 documentation https://getbootstrap.com/docs/4.4/components/navs/#tabs -->
  <ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
    </li>
  </ul>

  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
    <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">...</div>
    <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
  </div>

</body>

Заголовки вкладок (или элементы навигации) просто отображаются как обычный неупорядоченный список, а все фактическое содержимое вкладок отображается под ним.

Как я уже сказал, насколько я могу судить, файлы сценариев загружаются правильно. У меня есть средство выбора даты Bootstrap, настроенное и работающее на той же странице, но без стилей Bootstrap. Мне нужно использовать файл bootstrap-datepicker.standalone.css, потому что bootstrap-datepicker.min.css не работает.

Что я пробовал, но не помогло:

  • Удаление класса WebConfig
  • Перемещение ссылок css в тело HTML-документа
  • Ставить '/' перед @{webjars/...} в тегах ссылок. Технически это работает для Javascript, но не имеет значения для ссылок css. Кроме того, мне нужно убрать начальный «/», чтобы приложение использовало относительные ссылки на страницы, иначе приложение не будет работать при развертывании в нашей тестовой среде.
  • Указание версии внутри th:href вот так: @{/webjars/bootstrap/4.1.1-1/css/bootstrap.min.css}
  • Удаление других вещей с основной HTML-страницы до тех пор, пока она не будет тестировать только вкладки Bootstrap (т.е. только импортировать файлы Bootstrap css и Javascript)
  • Удаление th: из элемента ссылки

Единственное, что я работает, — это использование BootstrapCDN, как показано на https://getbootstrap.com/ : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Если я использую это вместо ссылки, которая у меня есть в HTML выше, стили применяются, и все работает (насколько я могу судить). Тем не менее, я хотел бы знать, почему я не могу заставить webjar работать, и если у кого-то еще была эта проблема. Или, может быть, я делаю что-то явно неправильное, чего я слишком близко не вижу?


person Cody S    schedule 01.05.2020    source источник


Ответы (1)


У меня была такая же (или очень похожая) проблема с использованием Bootstrap 4.5.0. Ниже сработало для меня:

В пом у меня есть:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.40</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.5.0</version>
</dependency>

У меня нет класса @Configuration - он фактически начал работать, когда я его удалил.

Мой html начинается с:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" type="text/css"/>
    <script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
</head>

Надеюсь это поможет.

РЕДАКТИРОВАТЬ: только что снова посмотрел на ваш код. У вас type="text.css" вместо type="text/css"

B.

person Bart B    schedule 31.05.2020