如何修复 spring 框架上的“白标错误页面” - GET 请求不起作用

ofe*_*ael 2 java get spring-mvc spring-boot spring-restcontroller

我正在尝试使用 spring boot 制作“Hello World”控制器,但 GET 请求不起作用。我能做些什么来解决这个问题?

我在https://start.spring.io/和我选择 web 的依赖项中使用了 spring 初始值设定项

我尝试使用不同的注释,如@GetMapping

package com.example.hello;

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

@RestController
public class HelloController {

    @RequestMapping("/")
    public String helloWorld() {
        return "Hello World";
    }
}

Run Code Online (Sandbox Code Playgroud)
<?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 http://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.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

Run Code Online (Sandbox Code Playgroud)
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

}

Run Code Online (Sandbox Code Playgroud)

我希望输出为“Hello World”,但实际输出为“Whitelabel Error Page”

nul*_*ptr 5

该问题与您的项目结构有关,默认情况下 Spring Boot 将扫描您的主应用程序类下面的组件。

在您的情况下,您的 main 位于package com.example.demo;,您的控制器位于package com.example.hello;

我建议您将控制器保存在包下方的新包中com.example.demo,就像文档中com.example.demo.controller提到的结构一样。

如果您真的要使用该com.example.hello包,则可能需要添加@ComponentScan("com.example.hello"),这在将来变得难以维护。

更多信息可以在这里找到。