繁体   English   中英

Spring 引导 Controller 未映射(Whitelabel 错误页面)

[英]Spring Boot Controller not mapping (Whitelabel Error Page)

我有一个 Spring REST 项目将所有请求重定向到错误页面,即使它们映射到 controller。

我将代码减少到可能产生错误的最小版本:

这是项目结构:

在此处输入图像描述

这是应用程序 class(删除了导入以使线程更易于阅读):

package com.example.demo;

@Controller
@SpringBootApplication
public class TestApplication {


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


    @GetMapping("/greeting")
    @ResponseBody
    public String greeting() {
        return "greeting";
    }

}

最初我从应用程序 class 中获得了一个单独的 controller,但是将 controller 代码移到了应用程序 class 以确保这不是项目结构问题这里是 controller 代码(尝试使用和不使用它,并收到相同的错误):

@Controller
@SpringBootApplication
public class TestApplication {


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


    @GetMapping("/hello")
    @ResponseBody
    public String greeting() {
        return "greeting";
    }

}

(http://localhost:8080/greeting 和 http://localhost:8080/hello 都返回相同的错误页面)

pom 文件中的依赖项和插件:

        <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>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
    

(尝试使用和不使用 tomcat 作为依赖项,但没有任何改变)

最后这是我访问链接时在浏览器中收到的错误消息(http://localhost:8080/greeting 和 http://localhost:8080/hello):

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Nov 27 00:16:08 CET 2022
There was an unexpected error (type=Not Found, status=404).

编辑:在 project.properties 中将 debug 设置为 true 后,这是我在控制台中看到的错误消息(值得一提的是,当我在另一个系统(同一操作系统)上尝试时,该项目运行没有任何问题):

 GET "/greeting", parameters={}
 Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
 Resource not found
 Completed 404 NOT_FOUND
 "ERROR" dispatch for GET "/error", parameters={}

(为了方便阅读,时间戳被删除)

您是否尝试通过 postman 拨打端点? 如果是这样,您可以在删除@ResponseBody 注释后重试。

而不是@Controller 使用@RestController

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM