Spring MVC应用配置欢迎文件后访问根路径出现404错误求助
回答
Hey there, let's break down why you're hitting that 404 and fix it up quickly.
核心原因
The main issue here is your DispatcherServlet is mapped to /—this means it takes over every request coming into your app, including the request for your welcome file index.jsp. When you hit http://localhost:8080/web_customer_tracker/, the server tries to load index.jsp, but instead of letting the container handle it, the DispatcherServlet steps in. It uses your view resolver settings (prefix /WEB-INF/view/, suffix .jsp) to look for /WEB-INF/view/index.jsp... which doesn't exist, hence the 404.
Your index.jsp is sitting in the web root, but the DispatcherServlet isn't looking there for views—it's only checking the /WEB-INF/view/ directory as configured.
解决方案 (按推荐程度排序)
1. 添加根路径控制器 (最佳实践)
Instead of relying on the welcome file mechanism, let Spring MVC handle the root route directly. This is cleaner and fits with Spring's design.
Create a simple HomeController (or add this to your existing CustomerController):
@Controller public class HomeController { @RequestMapping("/") public String redirectToCustomerList() { // 直接重定向到客户列表页面 return "redirect:/customer/list"; } }
Now when you hit the root URL, Spring will immediately redirect to /customer/list—no more welcome file confusion. Just make sure this controller is in the com.pindc.springdemo package so component scanning picks it up.
2. 移动index.jsp匹配视图解析器
If you really want to keep using the welcome file setup, move your index.jsp into the /WEB-INF/view/ directory (where all your other views are). Then update your web.xml welcome file entry to point to the correct path:
<welcome-file-list> <welcome-file>/WEB-INF/view/index.jsp</welcome-file> </welcome-file-list>
This works because now the DispatcherServlet will find the file when it looks for the index view. But honestly, the first method is better for Spring MVC apps.
3. 修改DispatcherServlet映射 (不推荐)
You could adjust the DispatcherServlet's URL pattern to something like *.html instead of /:
<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>
This lets the container handle welcome files normally, but it forces all your Spring routes to have a .html suffix, which is not RESTful and looks clunky. Avoid this unless you have a specific reason.
额外检查点
- Double-check your GlassFish deployment context root is exactly
web_customer_tracker(you can verify this in IntelliJ's Run/Debug configurations under the GlassFish server settings). - Make sure your
index.jspis actually in the web root directory (for Maven projects, that'ssrc/main/webapp; for non-Maven, it's thewebfolder marked as a Web Resource Root in IntelliJ). - Confirm your component scan (
<context:component-scan base-package="com.pindc.springdemo" />) covers your newHomeControllerif you go with option 1.
内容的提问来源于stack exchange,提问作者user7729696

