Ошибка 404, мой проект на самом деле не на локальном хосте или мой путь неправильный?

#java #spring-boot #api #rest

#java #пружинный ботинок #API #отдых

Вопрос:

Я пытаюсь создать свой первый rest API с помощью этого простого руководства h ttps://spring.io/guides/gs/rest-service/ и, похоже, не могу найти его в Интернете. Во-первых, он успешно устанавливается через mvn clean install, а затем, когда я запускаю на сервере с tomcat, он открывает браузер для http://localhost:8080/rest-service / но возвращает статус 404. Я пытался возиться с URL-адресом, чтобы указать разные конечные точки, но безуспешно. Я клонировал из «git clone https://github.com/spring-guides/gs-rest-service.git «

Попробовал:
http://localhost:8080/rest-service/greeting
http://localhost:8080/rest-service/greeting?name=test
http://localhost:8080/greeting?name=test
http://localhost:8080/gs-rest-service/greeting
http://localhost:8080/gs-rest-service/greeting?name=test

В руководстве говорится: «Когда вы закончите, вы можете сверить свои результаты с кодом в gs-rest-service / complete» мой проект не содержит полной папки.
В pom.xml:

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>rest-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rest-service</name>
    <description>Demo project for Spring Boot</description>
    <properties>
 

Сервер tomcat подключен к сети и запущен, потому что на нем размещены другие приложения, и я могу успешно найти их в браузере. Однако server.xml файл указывает, что номер порта равен 8089, тем временем я перехожу к http://localhost:8080/project_name чтобы найти другие проекты.

Контроллер Greating существует как таковой:

 @RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}
 

ОБНОВЛЕНИЕ С ПОМОЩЬЮ ЖУРНАЛА

 Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.43
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Jan 28 2021 20:25:45 UTC
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.43.0
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:UsersAHorner.p2poolpluginsorg.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.2.v20210201-0955jre
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           15.0.2 7-27
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:UsersAHornereclipse-workspaceeclipse-workspace-ee.metadata.pluginsorg.eclipse.wst.server.coretmp1
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:apache-tomcat-9.0.43
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:UsersAHornereclipse-workspaceeclipse-workspace-ee.metadata.pluginsorg.eclipse.wst.server.coretmp1
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:apache-tomcat-9.0.43
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:UsersAHornereclipse-workspaceeclipse-workspace-ee.metadata.pluginsorg.eclipse.wst.server.coretmp1wtpwebapps
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -XX: ShowCodeDetailsInExceptionMessages
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: Loaded Apache Tomcat Native library [1.2.26] using APR version [1.7.0].
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized [OpenSSL 1.1.1i  8 Dec 2020]
Mar 03, 2021 4:20:44 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Mar 03, 2021 4:20:44 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [1057] milliseconds
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Mar 03, 2021 4:20:44 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.43]
Mar 03, 2021 4:20:45 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:45 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:47 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:47 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:48 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:48 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 03, 2021 4:20:48 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Mar 03, 2021 4:20:48 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [3576] milliseconds
 

Комментарии:

1. Как вы запускаете свой сервер / проект? Вы запускаете его из IDE или с консоли? Можете ли вы показать нам какой-нибудь журнал?

2. Поделитесь своим журналом.

3. @Mannekenpix Я запускаю его из Eclipse. Щелкните правой кнопкой мыши, запустите на сервере. Я добавил журнал запуска сервера

Ответ №1:

Вы запускаете Tomcat, а не основной класс Spring Boot. Вы должны запустить этот класс: https://github.com/spring-guides/gs-rest-service/blob/master/complete/src/main/java/com/example/restservice/RestServiceApplication.java

Это основной класс Spring Boot, и он запустит встроенный Tomcat.

В руководстве указано:

Метод main() использует метод SpringApplication.run() Springappplication.run() Spring Boot для запуска приложения.