Подтвердить что ты не робот

Ошибка кругового просмотра пути Spring boot

Я очень новичок в Spring. Я пытаюсь создать приложение MVC с помощью Spring Boot, в котором отображается список продуктов. Но я получаю следующую ошибку:

javax.servlet.ServletException: Circular view path [products]: будет      снова отправьте URL-адрес текущего обработчика [/products]. Проверьте свои      Настройка ViewResolver! (Подсказка: это может быть результатом неуказанного      из-за генерации имени по умолчанию.)

Вот контроллер:

package com.springframeworkguru.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springframeworkguru.services.ProductService;


    @Controller
    public class ProductController {

        private ProductService productService;

        @Autowired
        public void setProductService(ProductService productService) {
            this.productService = productService;
        }

        @RequestMapping("/products")
        public String listProducts(Model model){

            model.addAttribute("products", productService.listAllProducts());

            return "products";
        }

    }

Это основной класс:

package com.springframeworkguru;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

import com.springframeworkguru.controllers.ProductController;

@SpringBootApplication
public class SpringmvcApplication extends SpringBootServletInitializer{

     public static void main(String[] args) {
        SpringApplication.run(SpringmvcApplication.class, args);
    }
}

и products.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Spring Core Online Tutorial - List Products</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link href="#" onclick="location.href='http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/css/bootstrap.min.css'; return false;"
          th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}"
          rel="stylesheet" media="screen"/>

    <script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.min.js"
            th:src="@{/webjars/jquery/2.1.4/jquery.min.js}"></script>

    <link href="../css/spring-core.css"
          th:href="@{css/spring-core.css}" rel="stylesheet" media="screen"/>
</head>
<body>
<div class="container">
    <div th:if="${not #lists.isEmpty(products)}">
        <h2>Product List</h2>
        <table class="table table-striped">
            <tr>
                <th>Id</th>
                <th>Description</th>
                <th>Price</th>
                <th>Image URL</th>
                <th>List</th>
            </tr>
            <tr th:each="product : ${products}">
                <td th:text="${product.id}"></td>
                <td th:text="${product.description}"></td>
                <td th:text="${product.price}"></td>
                <td th:text="${product.imageUrl}"></td>
                <td><a th:href="${'/product/' + product.id}">View</a> </td>
            </tr>
        </table>
    </div>
</div>

</body>
</html>

products.html находится в папке /static. Кроме того, я использую Eclipse Kepler.

4b9b3361

Ответ 1

Добавление зависимости spring-boot-starter-thymeleaf решило проблему.

Так что добавьте это в ваш файл pom.xml:

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

Обновление: если вы работаете с Eclipse и используете Gradle, это может не сработать. Причина в том, что если вы не импортировали проект как "gradle project", Eclipse не обнаружит тимилиф. Итак, вот решение:

Шаг 1: Запустите "gradle eclipse" в командной строке.

Шаг 2: Запустите "Gradle Wrapper"

Шаг 3: В eclipse import as gradle project (перед этим удалите уже импортированный проект)

Шаг 4: Теперь запустите, используя Eclipse

Шаг 5: Наслаждайтесь!

Ответ 2

Продукты .html - это/статическая папка

По умолчанию Spring Boot будет искать шаблоны Thymeleaf в каталоге templates в пути к классам. Поэтому переместите каталог products.html в src/main/resources/templates. Вы можете больше узнать о механизмах шаблонов и Spring Загрузка в Spring Загрузочная документация:

Когда вы используете механизм моделирования шаблонов тимелеафа по умолчанию конфигурации, ваши шаблоны будут автоматически загружены из src/main/resources/templates

Кроме того, каталог static предназначен для размещения статического содержимого, а не для ваших шаблонов.

Ответ 3

Добавьте следующую зависимость в pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

Последнюю версию можно найти на mvnrepository

Ответ 4

Вы можете быть здесь, потому что вы забыли поместить @RestController вашего контроллера отдыха над классом :)

Ответ 5

Переименуйте "product.ftl" в "product s.ftl".

Ответ 6

Проблемы могут быть вызваны использованием встроенного контейнера сервлетов (встроенного кота). @mirmdasif ответ

Чтобы решить эту проблему, используйте внешний сервер Tomcat.

Настройте сервер Tomcat в STS/Eclipse:
1. из верхнего меню: Window > Show View > Servers
2. в контекстном меню окна вкладки серверов: New > Server
3. выполнить настройку проекта для развертывания файла WAR в Tomcat.
4. запустить проект как Spring Boot App

развернуть файл WAR в Tomcat
Главный класс должен расширять SpringBootServletInitializer и переопределять метод SpringApplicationBuilder...

package package_with_your_main_class;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class YourStartWebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(YourStartWebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(YourStartWebApplication.class);
    }
}

pom.xml должен содержать

<!-- Parent pom providing dependency and plugin management for applications -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <!-- this version works with tomcat 8.5, change to newest if you are using newer tomcat -->
    <version>2.0.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <java.version>1.8</java.version>
    <!-- The main class to start by executing java -jar -->
    <start-class>package_with_your_main_class.SpringBootWebApplication</start-class>
</properties>

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

    <!-- templating language -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId> 
    </dependency>

    <!-- marked the embedded servlet container as provided -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

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

<packaging>war</packaging>

Ответ 7

Ну, у меня была та же проблема с использованием SpringBoot, и все, что я сделал, это заменить @Controller с @RestController, и он работал нормально.