Spring项目无法直接访问localhost:8080/,需加项目名才能打开首页
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.waras the default root application, solocalhost: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.xmlin Tomcat'sconf/Catalina/localhostdirectory. - Add this content to the file:
<Context docBase="/path/to/your/project/war/file" path="" /> - Replace
/path/to/your/project/war/filewith 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.jspis located atWEB-INF/view/home.jsp(matches yourViewResolverprefix/suffix). - The
@ComponentScaninApplicationConfigis correctly targeting your controller package (com.company.projectname). - Your
MvcDispatcherServletInitializeris 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

