You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot应用控制器无响应问题的排查与解决

Spring Boot访问localhost:8080出现404的解决方法

问题描述

我正在学习Spring Boot,尝试访问http://localhost:8080来获取控制器的响应,但浏览器显示404页面。

控制器代码

package com.learning.helloworld;

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

@RestController
public class ProductController {
    @GetMapping
    public String product(){
        System.out.println("Hi");
        return "the product is sold";
    }
}

pom.xml配置

<?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 https://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>3.0.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.learning</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>helloworld</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>19</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>

解决步骤

  • 检查启动类包路径
    Spring Boot默认只扫描启动类所在包及其子包下的组件。如果你的启动类(如HelloworldApplication)位于com.learning包,控制器在com.learning.helloworld子包,这是符合规则的;若启动类在其他包,需在启动类上添加@SpringBootApplication(scanBasePackages = "com.learning.helloworld"),手动指定扫描路径。

  • 给@GetMapping明确指定路径
    当前控制器的@GetMapping未指定路径,默认映射到/,可能存在冲突或识别问题。可以修改为@GetMapping("/product"),然后访问http://localhost:8080/product测试。

  • 查看应用启动日志
    启动应用时,检查控制台日志,确认是否有ProductController被加载的记录,比如类似Mapping GET "/" to public java.lang.String com.learning.helloworld.ProductController.product()的日志。如果没有该日志,说明控制器未被扫描到,回到第一步排查包路径问题。

  • 确认端口是否正确
    检查日志中是否有Tomcat started on port(s): 8080 (http)的信息,若端口被占用,Spring Boot会自动切换到其他端口,此时需访问日志中显示的对应端口。

内容的提问来源于stack exchange,提问作者Habibur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:43:17