java 弹簧靴 | 本地主机:显示 8080 404 错误页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43399196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:24:19  来源:igfitidea点击:

Spring Boot | localhost: 8080 404 error page displayed

javaspring-boot

提问by Jared Hart

I created a Spring Boot Maven project, however my RequestMapping, as well as localhost:8080 return a 404 error page. I think the issue is with how my packages are setup, but I've tried solutions in multiple questions, and I still cant get around the error page. Could you guys point me in the right direction as to how to resolve this issue? Perhaps I need to add the Component annotation above my Main class? But I've tried this solution, and the error still persists.

我创建了一个 Spring Boot Maven 项目,但是我的 RequestMapping 以及 localhost:8080 返回了 404 错误页面。我认为问题在于我的包是如何设置的,但我已经尝试了多个问题的解决方案,但我仍然无法绕过错误页面。你们能否指出我如何解决这个问题的正确方向?也许我需要在 Main 类上方添加 Component 注释?但是我已经尝试了这个解决方案,错误仍然存​​在。

Here is my package structure:

这是我的包结构:

 /src/main/java
      ControllerLayer
           UsersController.java
      DataAccessLayer
           UsersDAL.java
      ServiceLayer
           UsersService.java
      Main
           Main.java

Main.java:

主.java:

  @SpringBootApplication(scanBasePackages = { 
  "/src/main/java/ControllerLayer", "/src/main/java/DataAccessLayer", 
  "/src/main/java/ServiceLayer" })
  public class Main {

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

UsersController.java:

用户控制器.java:

 import Entities.Users;
 import ServiceLayer.UsersService;

 @RestController
 @RequestMapping("/users")
 public class UsersController {

      @Autowired
      private UsersService usersService;

      @RequestMapping(value = 
      "/create/{userId}/{userPassword}/{userAge}/{userEmail}"
      + "/{userFirstName}/{userlastName}", method = 
      RequestMethod.POST)

      public void createUser(@PathVariable("userId")String userId, 
      @PathVariable("userPassword")String userPassword, 
      @PathVariable("userAge")int userAge, 
      @PathVariable("userEmail")String userEmail,
      @PathVariable("userFirstName")String userFirstName, 
      @PathVariable("userLastName")String userLastName) {

           usersService.createUser(new Users(userId, userPassword, 
           userAge, userEmail, userFirstName, userLastName));
      }
   }

UserService.java

用户服务.java

 import DataAccessLayer.UsersDAL;
 import Entities.Users;

 @Service
 public class UsersService {

    @Autowired
    private UsersDAL usersDAL;

    public void createUser(Users user) {
         usersDAL.createUser(user);
    }
 }

pom.xml:

pom.xml:

 <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 
          http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>

      <groupId>xProjectAlpha</groupId>
      <artifactId>org.htech.xProjectAlpha</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>

      <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>1.5.2.RELEASE</version>
      </parent>

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

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

           <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.2.9.Final</version><!--$NO-MVN-MAN-VER$-->
           </dependency>
      </dependencies>

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

 </project>

采纳答案by cuongnguyen

When a request is sent, then a response shall be returned. In your case, you didn't send any content with the response and that's why you get 404 error (page not found).

当发送请求时,应返回响应。在您的情况下,您没有随响应发送任何内容,这就是您收到 404 错误(找不到页面)的原因。

回答by MuffinMan

In main.java, try:

在 main.java 中,尝试:

@SpringBootApplication(scanBasePackages = { 
  "ControllerLayer", "DataAccessLayer", 
  "ServiceLayer" })

Your package names shouldn't include the root path in the project.

您的包名称不应包含项目中的根路径。

回答by Sam2016

It is advisable to have spring boot Application class in root package and have all other classes in package structure below that package .You don't have to worry about component scan as an example

建议在根包中有 spring boot Application 类,并在该包下面的包结构中包含所有其他类。 例如,您不必担心组件扫描

package com.igt.customer;
import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class CustomerApplication {

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

     @Bean
        public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
            return args -> {

                System.out.println("Let's inspect the beans provided by Spring Boot:");

                String[] beanNames = ctx.getBeanDefinitionNames();
                Arrays.sort(beanNames);
                for (String beanName : beanNames) {
                    System.out.println(beanName);
                }

            };
        }
}

Controller class

控制器类

package com.igt.customer.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {
    @RequestMapping("/employee")
    public String employee() {
        return "Greetings from Sam!";
    }
}

running the application (go to the directory of your application on cmd )

运行应用程序(转到 cmd 上的应用程序目录)

E:\MongoDb\New folder\customer>mvn install -U -e

E:\MongoDb\New folder\customer>mvn install -U -e

you should see this in the end if its fine

如果没问题的话,你最后应该会看到这个

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.686 s
[INFO] Finished at: 2017-08-16T16:39:57+05:30
[INFO] Final Memory: 21M/219M
[INFO] ------------------------------------------------------------------------

run the jar file

运行jar文件

E:\MongoDb\New folder\customer\target>java -jar customer-0.0.1-SNAPSHOT.jar

E:\MongoDb\New folder\customer\target>java -jar customer-0.0.1-SNAPSHOT.jar

accessing the application

访问应用程序

http://localhost:8080/employee

http://localhost:8080/employee

Notice application name is not required in URL

注意 URL 中不需要应用程序名称

P.S i have written extra detail here as i have experienced if you are new to spring boot building and running the application is a challenge , in my application i had created a rest controller in the same package as the Application class with RequestMapping "/" as i was getting 404 error , Please see the link below as a reference

PS我在这里写了额外的细节,因为如果你不熟悉spring boot构建并且运行应用程序是一个挑战,我已经在我的应用程序中创建了一个rest控制器,它与带有RequestMapping“/”的Application类在同一个包中我收到 404 错误,请参阅下面的链接作为参考

spring boot application

弹簧启动应用程序

回答by Java_Explorer

This issue will be simply solved if you remove the main package of the main.java class.

如果删除 main.java 类的主包,这个问题将很容易解决。

The new structure will be:

新的结构将是:

/src/main/java
      Main.java
      ControllerLayer
           UsersController.java
      DataAccessLayer
           UsersDAL.java
      ServiceLayer
           UsersService.java

回答by HackPro

In my Springboot application, there is no need to scan the base packages manually because all the configurations are embedded in a single annotation @SpringBootApplication. Please refer to this link.

在我的Spring启动应用程序中,不需要手动扫描基础包,因为所有配置都嵌入在一个注释中@SpringBootApplication。请参阅此链接

I don't understand how the base packages are initially configured. Can someone please explain this?

我不明白基本包最初是如何配置的。有人可以解释一下吗?

For example, if your base package looks like:

例如,如果您的基本包如下所示:

com.example.myapp.SpringApplication

com.example.myapp.SpringApplication

... it means your application takes base packages as com.example.myapp. So if you can create all Controllers, Service, Repositoryunder com.example.myappin the sense it will load your Controllers, Service, Repositoryeasily or else it can't able to load. This is because springbootapplicationintially sets the base packages and loads whatever java classes are inside the base package. So because of this you get a 404error in the browser as well as in postman. So try to match with base package.

...这意味着您的应用程序将基本包作为com.example.myapp. 所以,如果你能创造一切ControllersServiceRepositorycom.example.myapp在这个意义上,将加载你的ControllersServiceRepository轻松,不然它无法负荷。这是因为springbootapplication最初设置基本包并加载基本包内的任何 java 类。因此,因此您会404在浏览器和postman. 所以尽量搭配基础包。