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

Spring项目无法直接访问localhost:8080/,需加项目名才能打开首页

Fixing HTTP 404 When Accessing localhost:8080/ Without Project Name in Spring MVC

Hey there, let's break down why you're seeing that 404 error and how to fix it. The core issue here is that your Servlet container (like Tomcat) is using your project name as the context path for your web application. When you visit localhost:8080/, the container doesn't associate that with your app—it's looking for a default root application instead.

Why This Happens

Your current configuration sets up the DispatcherServlet to handle all requests under your app's context path (which defaults to your project name). The @GetMapping("/") in your HomeController maps to [context-path]/, not the server's root /. That's why adding projectname to the URL works.

Solutions to Set Your App as the Root Context

1. Configure Your IDE's Server Deployment

If you're running the app from an IDE (IntelliJ, Eclipse, etc.):

  • Open your server run configuration.
  • Navigate to the Deployment tab.
  • Find the "Application context" field and change its value to /.
  • Restart the server—now localhost:8080/ should route directly to your app.

2. Rename Your WAR File (For Deployed Apps)

If you're packaging your app as a WAR file and deploying it to a standalone Servlet container:

  • Rename your WAR file to ROOT.war (all uppercase).
  • Servlet containers like Tomcat automatically treat the ROOT.war as the default root application, so localhost:8080/ will serve your app.

3. Add Context Configuration File (Tomcat Specific)

For standalone Tomcat deployments, you can also create a context file:

  • Create a file named ROOT.xml in Tomcat's conf/Catalina/localhost directory.
  • Add this content to the file:
    <Context docBase="/path/to/your/project/war/file" path="" />
    
  • Replace /path/to/your/project/war/file with the actual path to your WAR file, then restart Tomcat.

Verify Your Existing Configuration

Just to make sure nothing else is off, double-check these points:

  • Your home.jsp is located at WEB-INF/view/home.jsp (matches your ViewResolver prefix/suffix).
  • The @ComponentScan in ApplicationConfig is correctly targeting your controller package (com.company.projectname).
  • Your MvcDispatcherServletInitializer is properly registered (it should be picked up automatically by the Servlet container if you're using Servlet 3.0+).

That should resolve the 404 issue and let you access your home page directly at localhost:8080/.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:14:47